【问题标题】:Removing first string character with substr in WordPress在 WordPress 中使用 substr 删除第一个字符串字符
【发布时间】:2021-01-28 20:21:57
【问题描述】:

我正在尝试删除“|”从文件大小跨度标签。到目前为止,我的 javascript 代码的语法看起来不错,但它还不能正常工作。

据我了解,我使用了正确的 substr 语法:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr

在 Chrome 中,我收到此控制台错误:

未捕获的类型错误:无法读取未定义的属性“substr”

在 Firefox 中,我收到此控制台错误:

未捕获的类型错误:innerTextString 未定义。

还有“|”没有按预期删除。有什么想法我在这里出错了吗?

提前谢谢你。

<script>
    const prettyLinkRightFileSize = document.querySelectorAll('.prettyFileList .float_right:nth-child(1)');
    const innerTextString = prettyLinkRightFileSize.innerText;
    innerTextString.substr(0);
</script>
.prettyFileList .float_right {
    float: right;
}
<div class="prettyFileList">
    <div>
        <a href="#" class="prettylink">
            <span class="float_right">| Size 150 KB</span>
            <span class="float_right">28th Jan 2021</span> 
        </a>
    </div>
</div>

【问题讨论】:

标签: javascript ecmascript-6 substring substr bem


【解决方案1】:

当您使用 innerTextString.substr(0) 时,您不会裁剪任何内容,因为它与原始字符串具有相同数量的字符。

var e = "ThisisaText";
var t = e.substring(0);

Log.v("e", e);
Log.v("t", t);

输出:

"ThisisaText"
"ThisisaText"

此外,您还可以通过类名选择项目。所以我建议,你裁剪所有具有相同类的项目以提供一致性。

试试这个代码:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="prettyFileList">| Testsize</div>
</body>
<script>
    var c = document.getElementsByClassName('prettyFileList');
    for (var i = 0; i < c.length; ++i) {
      var item = c[i];  
      item.innerHTML = item.innerHTML.substr(1);
    }
</script>
</html>

【讨论】:

    【解决方案2】:

    querySelectorAll() 返回一个静态(非实时)NodeList。您需要使用prettyLinkRightFileSize[0].innerText

    【讨论】:

      【解决方案3】:

      const prettyLinkRightFileSize = document.querySelectorAll('.prettyFileList .float_right:nth-child(1)');

      const innerTextString = prettyLinkRightFileSize.innerText;

      收件人

         const prettyLinkRightFileSize = document.querySelector('.prettyFileList .float_right:nth-child(1)');`
      
         let innerTextString = prettyLinkRightFileSize.innerText;
      
         innerTextString = innerTextString.slice(1);
      
         console.log(innerTextString)
      

      【讨论】:

        【解决方案4】:

        这样就可以了:

        <script>
            Array.from(document.querySelectorAll('.prettyFileList .float_right:first-child'))
            .map(element => element.innerText = element.innerText.substring(1));
        </script>
        

        它还适用于您页面上的多个元素

        如果您执行 querySelectorAll,您将获得一个 nodeList,其中包含与 select 语句匹配的所有元素。你必须遍历这些结果来操作它们中的每一个(如果你只匹配一个元素:一个元素的数组仍然需要其他处理而不是它自己的元素)。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-06-24
          • 1970-01-01
          • 2011-06-01
          • 1970-01-01
          • 1970-01-01
          • 2012-09-23
          • 2011-05-29
          • 2012-11-27
          相关资源
          最近更新 更多