gpt4 book ai didi

javascript - 检测一个单词并将Class添加到正文

转载 作者:行者123 更新时间:2023-12-02 18:31:38 25 4
gpt4 key购买 nike

下面的 jQuery 检测到单词 firstthird在任何 <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")
});

来源:https://jsfiddle.net/fk05dabw/

关于javascript - 检测一个单词并将Class添加到正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69332786/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com