这是我方便的花花公子代码:
$('#options th.subhead').each(function(){$(this).parents('table').find('td:nth-child('+$(this).prevAll().length+')').andSelf().toggle();});
现在......理论上,我认为这应该做的是将表中的“subhead”类作为选项,然后找到同一列的任何td并切换它。哦,还有原来的那个。
猜猜是什么。它会清除并返回表格的全部内容。
我在这里遗漏了一些东西。我正在做的“这个”是preVall和长度不再是我想到的吗?
更新! wirey让我更接近他的评论。
我现在在这里:
$('#options th.subhead').each(function(){$(this).parents('table').find('td:nth-child('+$(this).prevAll().length+')').toggle();}).toggle();
除非隐藏错误的td,否则它的效果很好。它似乎是第一列上的一列,在最后一列左侧的下一个和一列上是正确的。 LOL
更新2.5(由于网址错误):
我做了一个小提琴 http://jsfiddle.net/MatthewDavis/8nTXB/1/更新3 得到它归功于线索。这是最后的小提琴! http://jsfiddle.net/MatthewDavis/8nTXB/2/
完成的代码行。
$('#options th.subhead').each(function () {
$(this).parents('table').find('td:nth-child(' + ($(this).prevAll().length+1) + ')').toggle();
}).toggle();
答案 0 :(得分: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索引且不是零 - 因此你需要在prevAll()中加1.length
$('#options th.subhead').each(function () {
$(this).parents('table').find('td:nth-child(' + ($(this).prevAll().length+1) + ')').toggle();
}).toggle();