下面的 jQuery 检测到单词 first
和third
在任何 <p>
文本并为其添加黄色或红色背景。
$(document).ready(function(){
$("p:contains(first)").css("background-color", "yellow");
$("p:contains(third)").css("background-color", "red");
});
<p>I'm the first sentence.</p>
<p>I'm the second sentence.</p>
<p>I'm the third sentence.</p>
<p>I'm the fourth sentence.</p>
JSFiddle:https://jsfiddle.net/3p0nmw4f/1/
但是,我不想突出显示文本,而是想 addClass
像这样的 html 文档正文:
<body class="first">
或
<body class="third">
我知道我们可以使用$(document.body).addClass('first');
来实现这一点但我无法将它们组合在一起。
请帮忙。
最佳答案
您可以搜索最接近的正文 HTML 元素。 您可以通过执行以下操作来做到这一点:
$(document).ready(function(){
$("p:contains(first)").closest('body').addClass('first');
$("p:contains(third)").closest('body').addClass('third');
});
另一种可能性是简单地搜索 body 元素,如下所示:
$(document).ready(function(){
if ($("p:contains(first)"))
$("body").addClass("first")
if ($("p:contains(third)"))
$("body").addClass("third")
});
关于javascript - 检测一个单词并将Class添加到正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69332786/