开发者

jQuery: highlight even columns (not rows)

How to colorize even (or odd) table columns using jQuery? (without adding classes manually)

My markup is:

<table>
   <caption>Table caption</caption>
   <thead>
   <tr><th scop开发者_运维技巧e="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>

(it may or may not contain scope attribs or th tags)


You can use the :nth-child() selector for this:

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

You can see a demo here, this version does the columns, regardless if the cell is a <th> or <td> you can add that in there (e.g. td:nth-child(2n)) if you want to do only one or the other. If you want to select the other columns, just do 2n+1 instead. ​


Edit: Updated to fix my misreading of the question.

This should work:

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

or

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜