Jquery 将html附加到使用“查找”的文本中;包括「;

Jquery 将html附加到使用“查找”的文本中;包括「;,jquery,append,contains,Jquery,Append,Contains,我想在查找文本时将html附加到文本: $( "div:contains(']')" ).append("<br>"); $(“div:contains(']')”)。追加(”); 。。这是错误的,因为我想针对这个特定的文本添加html,而不是在整个div中添加html。您需要迭代匹配元素所具有的文本节点,并在每个文本节点中,在其值中找到“]”。当文本节点具有此字符时,将文本节点拆分为两个,并在两者之间插入元素 以下是一些您可以使用的代码

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

 $( "div:contains(']')" ).append("<br>");
$(“div:contains(']')”)。追加(
”);

。。这是错误的,因为我想针对这个特定的文本添加html,而不是在整个div中添加html。

您需要迭代匹配元素所具有的文本节点,并在每个文本节点中,在其值中找到“]”。当文本节点具有此字符时,将文本节点拆分为两个,并在两者之间插入

元素

以下是一些您可以使用的代码:

$( "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);
        }
    });
});
$(“div:contains(']')”)。每个(函数(){
$(this).contents().each(函数(){
if(this.nodeType!==3)return;//只对文本节点感兴趣
设i;//“]”的位置。
而((i=this.nodeValue.indexOf(“])>=0){
$(this).before(this.nodeValue.slice(0,i+1),$(“
”); this.nodeValue=this.nodeValue.slice(i+1); } }); });