问题
it should be simple but this jQuery function are taking a element to much, it even hide the jQuery I think.
What I will like to do, is when a person click a tr th, all next tr td should be hide until next tr th.
How can I get this code to work??
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<style>
th { background:#dad;
font-weight:bold;
font-size:16px;
width: 50%;
}
td { background:red;
font-weight:bold;
font-size:16px;
width: 50%;
}
</style>
</head>
<body>
<table id="example">
<tr>
<th>
<button>Show it 3</button>
</th>
</tr>
<tr>
<td>test 1</td>
</tr>
<tr>
<td>test 2</td>
</tr>
<tr>
<th>
<button>Show it 2</button>
</th>
</tr>
<tr>
<td>test 3</td>
</tr>
<tr>
<td>test 4</td>
</tr>
</table>
<script>
$('#example tr th').click( function() {
//alert($(this).parent().html())
$(this).parent().nextUntil('tr th').toggle();
})
</script>
</body>
</html>
回答1:
you can add a class to he tr
elements that has th
element:
<table id="example">
<tr>
<th class='toggle'>
<button>Show it 3</button>
</th>
</tr>
<tr>
<td>test 1</td>
</tr>
<tr>
<td>test 2</td>
</tr>
<tr class='toggle'>
<th>
<button>Show it 2</button>
</th>
</tr>
<tr>
<td>test 3</td>
</tr>
<tr>
<td>test 4</td>
</tr>
</table>
$('#example tr th').click( function() {
$(this).parent().nextUntil('.toggle').toggle();
})
DEMO
回答2:
Here's a way to do it using mostly the 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;
}
}
Or, with more 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;
}
});
来源:https://stackoverflow.com/questions/11414965/hide-all-next-tr-td-until-next-tr-th