2010-05-06 64 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; 
    } 
};