隐藏所有下一个tr td直到下一个tr th

它应该很简单但是这个jQuery函数占用了很多元素,它甚至隐藏了我认为的jQuery。

我想做的是,当一个人点击一个tr时 ,所有下一个tr td应该隐藏到下一个tr

我怎样才能使这段代码工作?

     th { background:#dad; font-weight:bold; font-size:16px; width: 50%; } td { background:red; font-weight:bold; font-size:16px; width: 50%; }    
test 1
test 2
test 3
test 4
$('#example tr th').click( function() { //alert($(this).parent().html()) $(this).parent().nextUntil('tr th').toggle(); })

你可以为具有th元素的tr元素添加一个类:

 
test 1
test 2
test 3
test 4

 $('#example tr th').click( function() { $(this).parent().nextUntil('.toggle').toggle(); }) 

DEMO

这是一种主要使用dom的方法

  $('#example tr td button').on('click',function(e){ var curr = this; // get the tr where the button was clicked while(curr.nodeType!=='tr') curr = curr.parentNode; // now get sibling nodes while((curr=curr.nextSibling)){ if(curr.firstChild.nodeType==='td') $(curr).hide(); else if(curr.firstChild.nodeType==='tr') return; } } 

或者,使用更多jQuery:

 $('#example tr td button').on('click',function(e){ var siblings = $(this).siblings(); for(var i=0; i < siblings.length; i++){ if(siblings[i].find('td').length) $(siblings[i]).hide(); else if(siblings[i].find('tr').length) return; } });