2010-07-06 60 views
5

如何使用jQuery爲偶數(或奇數)表格列着色? (不添加人工班)jQuery:突出顯示偶數列(不是行)

我的標記是:

<table> 
    <caption>Table caption</caption> 
    <thead> 
    <tr><th scope="col">Table header 1</th><th scope="col">Table header 2</th><th scope="col">Table header 3</th><th scope="col">Table header 3</th></tr> 
    </thead> 
    <tbody> 

     <tr><th scope="row">Table row header</th><td>Table data</td><td>Table data</td><td>Table data</td></tr> 
     <tr><th scope="row">Table row header</th><td>Table data</td><td>Table data</td><td>Table data</td></tr> 
     <tr><th scope="row">Table row header</th><td>Table data</td><td>Table data</td><td>Table data</td></tr> 

     <tr><th scope="row">Table row header</th><td>Table data</td><td>Table data</td><td>Table data</td></tr> 
    </tbody> 
</table> 

(它可能會或不會包含範圍attribs或th標籤)

回答

6

可以使用:nth-child() selector此:

$('table tr :nth-child(2n)').css('background-color', '#eee'); 

You can see a demo here,這個版本做的是列,無論單元是否是<th><td>你可以在那裏添加(例如td:nth-child(2n))如果你只想做一個或另一個。如果您想要選擇其他列,請改爲使用2n+1

+0

+1:感謝您對我的回答您的評論,在這裏提供正確的解決方案。 – Sarfraz 2010-07-06 15:21:43

+0

謝謝,這一個工作正常(以前的版本做過某種跳棋;) – Adrian 2010-07-06 15:27:46

+0

需要更多代表upvote :) – Adrian 2010-07-06 15:28:30

1

編輯:更新以解決我對該問題的誤讀。

這應該工作:

$('tr > :nth-child(even)').css('background-color','#eee'); 

$('tr > :nth-child(odd)').css('background-color','#eee'); 
+0

肯 - OP是着色列,而不是行。 :o) – user113716 2010-07-06 15:25:33

+0

@帕特里克:哎呀,你說得對。 – 2010-07-06 15:26:01

+0

這是一個着色行,我需要*列* – Adrian 2010-07-06 15:26:34