2010-05-06 66 views
5

我目前使用此代码将一个类添加到我表中的每一行。使用jquery选择隔行2表行

$(".stripeMe tr:even").addClass("alt"); 

然而,在另一个表我想添加一个类行3,4,7,8,11,12等等...

这可能吗?

+0

请提供表结构的一个片段! – 2010-05-06 15:07:23

+2

它的一个简单的表结构:

​​​​​​​​​​
Mark 2010-05-06 15:09:07

回答

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");​​​​​​​​​​​​​​​​​ 

You can see this working here

使用此:

$(".stripeMe tr:nth-child(4n), .stripeMe tr:nth-child(4n-1)").addClass("alt");​​​​​​​​ 

gets different results(即WebKit中,可能还有其他人)。

+0

这对我很有用,非常感谢。 – Mark 2010-05-06 15:27:29

+0

如何才能将不同的css类应用于前两行?谢谢btw! – Mark 2010-05-06 15:29:53

+0

@Mark - 如果你的意思只是**非常**第一个2,那么就像这样:'$(“。stripeMe tr:lt(2)”)。addClass(“otherClass”);'' – 2010-05-06 15:34:18

3

随着`:第n-child'选择:http://api.jquery.com/nth-child-selector/

$(".stripeMe tr:nth-child(4n), .stripeMe tr:nth-child(4n-1)").addClass("alt"); 
+0

这不工作:) http://jsfiddle.net/ndn67/ – 2010-05-06 15:11:05

+0

你的例子适合我... – RoToRa 2010-05-06 15:14:01

+0

@RoToRa - Ope它在webkit :) – 2010-05-06 15:14:49

1

可以使用filter功能来过滤设定你喜欢的任何方式:

$(".stripeMe tr") 
.filter(function(i){ return (i % 4) >= 2; }) 
.addClass("alt"); 

这将保持与指数2,3,6,7,10,11等的项目。请注意,该索引是基于零的,因此第三行为索引二。

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; 
    } 
};