使用jQuery选择第n列中的所有单元格

Select all cells in nth column with jQuery

本文关键字:单元格 jQuery 选择 使用      更新时间:2023-09-26

如何选择普通html表的第n列中的所有单元格?我试过了,但是没有用:

    $('table#foo tbody td:nth-child(3)').each(function (index) {
        $(this).addClass('hover');
    });

更新:下面是一些无法正常工作的代码:http://jsfiddle.net/Claudius/D5KMq/

不需要使用each

$('table#foo tbody td:nth-child(3)').addClass('hover');

除此之外,你的代码没有任何问题。

您的实际问题(在原始问题中不明显,但在提琴中存在)是.index()返回基于零的值,但:nth-child()需要基于1的值。

$('table#foo tbody td:nth-child(3)').addClass('hover');

使用这个脚本(请注意,使用:n -child选择器来匹配每个子节点的索引,从1开始)

$(".legendvalue", ".stmatst_legends").hover(function() {
    var index = $('.legendvalue').index($(this));
    $('table#stmstat tbody td:nth-child(' + (index + 1) + ')').addClass('hover');

}, function() {
    //remove hover
});