-1

这是我方便的花花公子代码行:

$('#options th.subhead').each(function(){$(this).parents('table').find('td:nth-child('+$(this).prevAll().length+')').andSelf().toggle();});

现在......理论上,我认为这应该做的是将表中带有“子标题”类的任何选项作为选项,然后找到同一列的任何 td 并切换它。哦,还有原来的th。

你猜怎么了。它清除并返回表的全部内容。

我在这里遗漏了一些东西。我正在做 preVall 和长度的“这个”不再是我想的这个吗?

更新!威利的评论让我更接近了。

我现在在这里:

$('#options th.subhead').each(function(){$(this).parents('table').find('td:nth-child('+$(this).prevAll().length+')').toggle();}).toggle();

这很好用,除非它隐藏了错误的 td。它似乎是第一列上的一列,接下来的两列是正确的,最后一列的左侧是一列。哈哈

更新 2.5(由于 url 错误):

我做了一个小提琴 http://jsfiddle.net/MatthewDavis/8nTXB/1/

更新 3 感谢wirey。这是最后的小提琴! http://jsfiddle.net/MatthewDavis/8nTXB/2/

以及完整的代码行。

$('#options th.subhead').each(function () {
    $(this).parents('table').find('td:nth-child(' + ($(this).prevAll().length+1) + ')').toggle();
}).toggle();
4

1 回答 1

1

这是你的错误

$('#options th.subhead').each(function(){
    $(this) // <-- you're at the th level
    .parents('table') // <-- now your at the table level
    .find('td:nth-child('+$(this).prevAll().length+')') // you traversed down
    .andSelf() // <-- this says add the previous element in the stack which is the table
    .toggle(); // here you are toggling the tds and the table
});

你这样尝试 - 未经测试

$('#options th.subhead').each(function(){
    $(this) // <-- you're at the th level
    .parents('table') // <-- now your at the table level
    .find('td:nth-child('+$(this).prevAll().length+')') // you traversed down
    .end()  // <-- now back at the table level in the stack
    .andSelf() // <-- this says previous elements in the stack which is the TH
    .toggle(); // here you are toggling the th and tds
});

仅供参考,如果您使用的是 jQuery 1.8+,那么您应该使用.addBack()代替,因为 .andSelf() 已被弃用

编辑

:nth-child是 1-indexed 而不是 0-inexed 所以你需要加 1 到 prevAll().length

$('#options th.subhead').each(function () {
  $(this).parents('table').find('td:nth-child(' + ($(this).prevAll().length+1) + ')').toggle();
}).toggle();
于 2013-01-28T21:40:58.233 回答