。
>假设我在HTML中有div和p,它们都包含相同的文本。我只想突出显示 html 段落中搜索的文本。我如何使用jQuery来做到这一点?
喜欢
<div>Hello</div>
<div>World</div>
<p>Hello</p>
<p>World</p>
我想突出显示段落标签中的"世界"。
可以将类添加到整个 p
元素。
$('p:contains("Hello")').addClass('highlight');
否则,您需要遍历文本节点,然后用 span
包装匹配。
使用:contains
选择器。
var str = "World";
$('p:contains('+str+')').css('background-color', 'yellow');
在这里摆弄
$('p').each(function(index) { // Find every paragraph and run through them
if($(this).text() === "world") { // Check if current paragraph's text is "world"
$(this).addClass("itemFound"); // Apply styling
}
});
这将执行不区分大小写的搜索并添加突出显示类。
var str = /world/gi;
jQuery("p").each(function() {
if(jQuery(this).text().match(str) {
jQuery(this).addClass("highlight");
}
});
在正文中使用这个
<script>
$("body").find("p").eq(1).css("background-color","green");
</script>