繁体   English   中英

<span>使用 jQuery</span>将特定文本字符串包装在 HTML 标签内

[英]Wrap a particular text string inside an HTML tag with a <span> using jQuery

我试图用span将给定 HTML 标签的文本内容中的某个单词(甚至单词的一部分)包装起来,使用 jQuery 或普通 javascript 对其应用 class。

我只选择了包含所需单词/字符串的完整标签,但我不知道如何 select 并将单词包装在其中。 我找到的所有方法都会搜索 substring,但总是搜索 select 并包装整个标签或其完整内容(例如wrapInner() ),这不是我想要的。

 $('h3:contains(icular)').wrap("<span class='highlight'></span>");
 .highlight { color: green; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h3>This is the first of several h3 headings</h3> <h3>This is another h3 heading, containing a particular word</h3> <h3>This is another h3 heading</h3> <h3>This is another h3 heading, again containing a particular word</h3> <h3>This is the way it should look: part<span class="highlight">iculär</span> word</h3> <p>This is ap tag, containing the same particular word/string. It should not be affected in this process.</p>

您可以使用.each()迭代所有包含您要查找的单词的元素,然后对每个元素的 html 执行.replaceAll()

 const search = 'icular' $('h3:contains(' + search + ')').each( function(index, element) { $(element).html( $(element).html().replaceAll(search, '<span class="highlight">' + search + '</span>') ) })
 .highlight { color: green; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h3>This is the first of several h3 headings</h3> <h3>This is another h3 heading, containing a particular word and another instance of the same "particular" word</h3> <h3>This is another h3 heading</h3> <h3>This is another h3 heading, again containing a particular word</h3> <h3>This is the way it should look: part<span class="highlight">iculär</span> word</h3>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM