【问题标题】:Append html to text which find with "contains"将 html 附加到找到“包含”的文本
【发布时间】:2020-12-07 11:23:58
【问题描述】:

我想在找到它时将 html 附加到文本中:

 $( "div:contains(']')" ).append("<br>");

.. 这是错误的,因为我想定位这个特定的文本并添加 html 而不是在整个 div 上附加 html。

【问题讨论】:

    标签: jquery append contains


    【解决方案1】:

    您需要迭代匹配元素具有的文本节点,并在每个文本节点的值中找到“]”。当文本节点有这个字符时,将文本节点一分为二,并在其间注入&lt;br&gt;元素。

    这里有一些你可以使用的代码:

    $( "div:contains(']')" ).each(function () {
        $(this).contents().each(function () {
            if (this.nodeType !== 3) return; // Only interested in text nodes
            let i; // position of the "]".
            while ((i = this.nodeValue.indexOf("]")) >= 0) {
                $(this).before(this.nodeValue.slice(0, i+1), $("<br>"));
                this.nodeValue = this.nodeValue.slice(i+1);
            }
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-25
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多