gpt4 book ai didi

javascript - 有条件地将类添加到特定元素

转载 作者:行者123 更新时间:2023-11-28 11:35:15 25 4
gpt4 key购买 nike

我正在尝试编写一个 if 语句来检查 LI 元素的 html 是否与变量匹配,如果匹配,则向该特定 li 添加一个类。

我的 HTML:

<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>

到目前为止我已经尝试过:

var x = "Three";
if($('li').html() == x) {
$(this).addClass("active");
}

期望的结果:

<li>One</li>
<li>Two</li>
<li class="active">Three</li>
<li>Four</li>

最佳答案

我想你会想使用过滤方法:

var x = "Three";
$( "li" ).filter(function( index ) {

return $(this).html() == x;
}).addClass("active");

关于javascript - 有条件地将类添加到特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23502062/

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