我的 HTML 结构:
<div id="test-listing">
<article>
<a>Some URL</a><h3>Some Text</h3>
<p>Drink this coffee</p>
</article>
<article><a>Some URL</a><h3>Some Text</h3><p>Drink this Coffee</p></article>
<article><a>Some URL</a><h3>Some Text</h3><p>Drink this Coffeeland</p></article>
<article><a>Some URL</a><h3>Some Text</h3><p>Drink this coffees</p></article>
</div>
我的 CSS 类:
.hit-list {
background: none repeat scroll 0 0 rgba(255, 0, 0, 0.1);
border-bottom: 1px solid #FF0000;
}
我需要搜索文本 coffee,而不考虑区分大小写。请注意,咖啡文字可能类似于 coffee、coffees、Coffee、Coffeeland 并将其应用于特定类别。所以生成的代码将是
<div id="test-listing">
<article><a>Some URL</a><h3>Some Text</h3
<p>Drink this <span class="hit-list">coffee</span></p>
</article>
<article><a>Some URL</a><h3>Some Text</h3
<p>Drink this <span class="hit-list">Coffee</span></p>
</article>
<article><a>Some URL</a><h3>Some Text</h3
<p>Drink this <span class="hit-list">Coffee</span>land</p>
</article>
<article><a>Some URL</a><h3>Some Text</h3
<p>Drink this <span class="hit-list">coffee</span>s</p>
</article>
</div>
我搜索了相关帖子,但没有找到任何东西,因为我正在处理循环内的内容。我也不需要 jQuery 插件来实现这一点。
谢谢。
最佳答案
你可以这样做:
$('div#test-listing article').html(function () {
return $(this).html().replace(/coffee(?=[^>]*<)/ig, "<span class='hit-list'>$&</span>");
});
如果搜索词是动态的,您可以这样做:
var term = 'coffee';
$('div#test-listing article').html(function () {
return $(this).html().replace(new RegExp(term + "(?=[^>]*<)","ig"), "<span class='hit-list'>$&</span>");
});
关于jQuery 查找文本并添加类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23441264/