使用jQuery为具有特定类的奇数行添加CSS

4

我有以下标记

<tr>
  <td>1,1</td>
</tr>
 <tr>
  <td>2,1</td>
</tr>
<tr class="add-css">
  <td>3,1</td>
</tr>

我想要为具有类add-css的奇数行添加背景颜色,我的简陋jQuery代码如下:
$( "tr" ).filter( ":odd" )hasClass('add-css').css( "background-color", "blue" );
2个回答

6
你在 hasClass 中漏掉了点号 .,而且 hasClass 返回的是布尔值,所以无法进一步链接需要 jQuery 对象的操作。你可以使用类型选择器和类选择器来解决问题。

.hasClass()

如果一个元素有指定的类,则 .hasClass() 方法返回 true。

即使其他类也存在,.hasClass() 方法也会返回 true。
$( "tr.add-css" ).filter( ":odd" ).css( "background-color", "blue");

或者

$( "tr.add-css:odd" ).css( "background-color", "blue");

@SadamAfridi 即使你在睡觉,浏览器也不会停止工作:它会在控制台中显示“未捕获的语法错误”。 - Regent

1
你可以尝试这个。
$( "tr:nth-child(odd)" ).each(function(index, element) {

    if($(this).hasClass('add-css')){
        $(this).css( "background-color", "blue" );
    }
});

甚至可以使用CSS来完成它。
tr.add-css:nth-child(odd){
    background-color:blue;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接