我正在尝试编写一个 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/