【问题标题】:Loop every alternate column in table in jQuery在jQuery中循环表格中的每个备用列
【发布时间】:2014-05-26 02:07:14
【问题描述】:

有没有办法遍历表中的每个备用列?

我想循环遍历表的 TD,但只遍历 2, 4, 6 and 8 列中的 TD。

如果有帮助,我还可以在这些列的 THsCOLs 中添加一个类。

我正在寻找类似以下的内容(只是为了演示):

$('#my table tbody (col2,col4,col6,col8)').each(function() {
    $('td').each(function() {
        //do stuff
    });
});

【问题讨论】:

    标签: jquery arrays loops each


    【解决方案1】:

    您可以使用nth-child() 选择器:

    $('#my table td:nth-child(even)').each(...);
    

    如果您想在 8 处停止,即使在那之后还有更多列(如大卫的回答),您可以以稍微复杂的方式进行:

    $('#my table td:nth-child(-2n+8)').each(...);
    

    (这是可行的,因为nth-child() 只考虑值 n >= 0)。

    【讨论】:

    • 非常感谢。这在 IE8 和 IE9 中是否支持?
    • 它是 jQuery 的一部分;它实际上并不依赖存在的 CSS nth-child 选择器。所以它应该适用于任何浏览器。
    【解决方案2】:
    $("#table td:nth-child(2)").each(function (index) {
       alert('Row: ' + (index+1) + ', Col : ' + $(this).html());
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-08
      • 2017-11-25
      • 2014-06-17
      • 1970-01-01
      • 2016-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多