【问题标题】:jQuery: highlight even columns (not rows)jQuery:突出显示偶数列(不是行)
【发布时间】:2011-03-12 08:58:41
【问题描述】:

如何使用 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>

(它可能包含也可能不包含范围属性或th 标签)

【问题讨论】:

    标签: jquery html css jquery-selectors


    【解决方案1】:

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

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

    You can see a demo here,此版本执行列,无论单元格是&lt;th&gt; 还是&lt;td&gt;,如果您只想执行其中一个,您可以在其中添加它(例如td:nth-child(2n))。如果您想选择 other 列,只需执行 2n+1 即可。 ​

    【讨论】:

    • +1:感谢您对我的回答发表评论并在此处提供正确的解决方案。
    • 谢谢,这个工作正常(以前的版本做了一些检查;)
    • 没有JS可以吗?仅 CSS3?
    • 这里值得注意的是,如果您的表中有任何行跨度,我认为这将不起作用,因为第二个孩子将不再是第二列。
    • 也感谢jsfiddle.net的链接,我不知道这个工具。
    【解决方案2】:

    编辑:更新以修正我对问题的误读。

    这应该可行:

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

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

    【讨论】:

    • Ken - OP 为列着色,而不是行。 :o)
    • 这个是着色行,我需要columns
    • Ken - 您忽略了 OP 所说的可能存在或不存在的 th 元素。 :o)
    猜你喜欢
    • 2011-12-01
    • 2014-10-03
    • 1970-01-01
    • 1970-01-01
    • 2017-05-24
    • 2010-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多