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

标签 javascript jquery if-statement

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

相关文章:

javascript - 在 map 视口(viewport)中显示所有地理 map 标记

javascript - 使用 map 时出现 ESlint 错误 - 解决方法?

javascript - 需要获取第 2 列的内容以跳转到移动设备的第 1 列

jquery - 动态改变div之间的页面内容?

Excel IF AND 语句在 true 时返回 false

javascript - ECharts中自定义字段名称

jquery - 仅选择 LI 项的 UL 子项

sql - 使用 IF…THEN Sql 查询并返回 int 和 String

java - if 语句中 x 可以等于一系列数字/数字范围?

javascript - 如何将对话框的创建移动到 jQuery UI 中的外部函数中?