我有以下标记
<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" );
hasClass
中漏掉了点号 .
,而且 hasClass
返回的是布尔值,所以无法进一步链接需要 jQuery 对象的操作。你可以使用类型选择器和类选择器来解决问题。
即使其他类也存在,如果一个元素有指定的类,则
.hasClass()
方法返回 true。
.hasClass()
方法也会返回 true。$( "tr.add-css" ).filter( ":odd" ).css( "background-color", "blue");
或者
$( "tr.add-css:odd" ).css( "background-color", "blue");
$( "tr:nth-child(odd)" ).each(function(index, element) {
if($(this).hasClass('add-css')){
$(this).css( "background-color", "blue" );
}
});
tr.add-css:nth-child(odd){
background-color:blue;
}