jquery:找到一个字符串并将其包装在<a>标签中?

Har*_*ldo 8 jquery

我有这个:

<div class="" id="fancy_hover">
    <a href="home.html" id="start_writer"></a>  
    <div>
        <p class="hidden" style="display: block;">click here to see this event with all the bells and whistles</p>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

我需要做一个等效的.find()但是对于字符串"click here"而不是节点,我需要将它包装在一个<a>标签中.

什么是jquery的最佳方法?

Sar*_*raz 19

使用:contains滤镜选择器:

$('p.hidden:contains("click here")')
Run Code Online (Sandbox Code Playgroud)

将其包装在链接中:

$('p.hidden:contains("click here")').html()
.replace('click here', '<a href="url">click here</a>');
Run Code Online (Sandbox Code Playgroud)

要在链接中包装整个文本:

$('p.hidden:contains("click here")')
.html('<a href="url">' + $('p.hidden:contains("click here")').text() + '<a>');
Run Code Online (Sandbox Code Playgroud)

更多信息:


bob*_*nce 7

不要使用HTML字符串黑客.想象一下,如果你试图<span title="blah click here blah">...</span><a>标签代替那么会发生什么......大量破坏的标记.这只是问题的开始.

相反,迭代在要检查,寻找文字匹配,将使用DOM式方法的新链接的文档的一部分文本节点.

jQuery在这里并没有真正帮助你,因为它没有处理文本节点的功能.相反,使用类似此问题中findText()函数并用于拆分文本节点:splitText

findText($('#fancy_hover')[0], /\bClick here\b/gi, function(node, match) {
    node.splitText(match.index+match[0].length);
    var link= document.createElement('a');
    link.href= 'http://www.example.com/';
    link.appendChild(node.splitText(match.index));
    node.parentNode.insertBefore(link, node.nextSibling);
});
Run Code Online (Sandbox Code Playgroud)