最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Select all cells in nth column with jQuery - Stack Overflow

programmeradmin7浏览0评论

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

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

UPDATE: Heres a jsfiddle of the unworking code: /

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

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

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

Share Improve this question edited Oct 19, 2011 at 13:26 Muleskinner asked Oct 19, 2011 at 13:17 MuleskinnerMuleskinner 14.5k20 gold badges62 silver badges81 bronze badges 5
  • 1 Have you got an example of the markup, in jsfiddle for example? – StuperUser Commented Oct 19, 2011 at 13:18
  • works for me ... jsfiddle/cefb7 – Manuel van Rijn Commented Oct 19, 2011 at 13:21
  • me too: jsfiddle/alnitak/XWyAn – Alnitak Commented Oct 19, 2011 at 13:24
  • Heres a jsfiddle: jsfiddle/Claudius/D5KMq – Muleskinner Commented Oct 19, 2011 at 13:25
  • Sorry forgot to include jquery, heres a update that seems to work jsfiddle/Claudius/D5KMq/2 – Muleskinner Commented Oct 19, 2011 at 13:30
Add a ment  | 

3 Answers 3

Reset to default 10

There is no need to use each for this.

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

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

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-based value.

$('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)

$(".legendvalue", ".stmatst_legends").hover(function() {
    var index = $('.legendvalue').index($(this));

    $('table#stmstat tbody td:nth-child(' + (index + 1) + ')').addClass('hover');


}, function() {
    //remove hover
});
发布评论

评论列表(0)

  1. 暂无评论