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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7821881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:26:32  来源:igfitidea点击:

Select all cells in nth column with jQuery

javascriptjqueryjquery-selectorscss-selectors

提问by Muleskinner

How do I select all cells in nth column of a normal html table. Ive tried this but its not working:

如何选择普通 html 表格的第 n 列中的所有单元格。我试过这个,但它不工作:

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

UPDATE: Heres a jsfiddle of the unworking code: http://jsfiddle.net/Claudius/D5KMq/

更新:这是无效代码的 jsfiddle:http: //jsfiddle.net/Claudius/D5KMq/

回答by fearofawhackplanet

There is no need to use eachfor this.

没有必要为此使用each

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

Other than that, there's nothing wrong with your code. Problem must be somewhere else.

除此之外,您的代码没有任何问题。问题一定出在其他地方。

回答by Alnitak

Your actual problem (not evident in the original question, but there in the fiddle) is that .index()returns a zero-based value, but :nth-child()requires a one-basedvalue.

您的实际问题(在原始问题中不明显,但在小提琴中)是.index()返回一个从零开始的值,但:nth-child()需要一个从一开始的值。

回答by Yuriy Rozhovetskiy

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

Use this script (draw your attention that with :nth-child selector index of each child to match, starting with 1)

使用这个脚本(请注意每个孩子的 :nth-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
});