2010-07-06 58 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