在jQuery中循环表中的每个备用列

问题描述 投票:1回答:2

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

我想循环一个表的TD,但只有那些列2, 4, 6 and 8

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

我正在寻找以下内容(仅用于演示):

$('#my table tbody (col2,col4,col6,col8)').each(function() {
    $('td').each(function() {
        //do stuff
    });
});
jquery arrays loops each
2个回答
3
投票

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

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

如果您想在8之后停止,即使之后有更多列(如David的回答),您可以稍微复杂一点的方式执行此操作:

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

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


1
投票
$("#table td:nth-child(2)").each(function (index) {
   alert('Row: ' + (index+1) + ', Col : ' + $(this).html());
});
© www.soinside.com 2019 - 2024. All rights reserved.