我目前正在使用此代码将类添加到表格中的每一行。
$(".stripeMe tr:even").addClass("alt");
但是,在另一个表格中,我想在第3,4,7,8,11,12行添加一个类......等等...
这可能吗?
答案 0 :(得分:8)
你需要这样做:
$(".stripeMe tr:nth-child(4n)").add(".stripeMe tr:nth-child(4n-1)").addClass("alt");
//or...
$("tr:nth-child(4n), tr:nth-child(4n-1)", ".stripeMe").addClass("alt");
使用此:
$(".stripeMe tr:nth-child(4n), .stripeMe tr:nth-child(4n-1)").addClass("alt");
gets different results(即在webkit中,可能是其他人)。
答案 1 :(得分:3)
使用`:nth-child'选择器:http://api.jquery.com/nth-child-selector/
$(".stripeMe tr:nth-child(4n), .stripeMe tr:nth-child(4n-1)").addClass("alt");
答案 2 :(得分:1)
您可以使用filter
功能以您喜欢的方式过滤设置:
$(".stripeMe tr")
.filter(function(i){ return (i % 4) >= 2; })
.addClass("alt");
这将保留索引为2,3,6,7,10,1等的项目。请注意,索引是基于零的,因此第三行作为索引2。
答案 3 :(得分:1)
我使用for循环和.eq()方法对此问题采用了不同的方法。
var a = 2; // start from 2 because eq() counts from 0
var b = 3; // start from 3 because eq() counts from 0
var total = $('.stripeMe td').length;
for (i = 0; i <= total; i++){
if (i == a){
$('.stripeMe tr:eq('+a+')').css('background', 'red');
a+=4;
}
else if (i == b){
$('.stripeMe tr:eq('+b+')').css('background', 'blue');
b+=4;
}
};