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

时间:2015-06-11 07:21:14

标签: jquery html css

我有以下标记

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

我想为具有类add-css的奇数行添加背景颜色,我的ruff jQuery代码是

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

2 个答案:

答案 0 :(得分:6)

您错过了.hasClass返回hasClass值的点boolean,因此无法进一步链接需要jQuery对象。您可以将类选择器与类型选择器一起使用。

.hasClass()

  

如果将类分配给.hasClass()方法将返回true   元件

如果将类分配给元素,则.hasClass()方法将返回true,即使其他类也是

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

OR

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

答案 1 :(得分: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;
}