Jquery 隐藏所有下一个tr td直到下一个tr th
它应该很简单,但是这个jQuery函数占用了很多元素,我认为它甚至隐藏了jQuery 我想做的是,当一个人点击一个tr th时,所有下一个tr td应该隐藏到下一个tr th 我怎样才能让这个代码工作Jquery 隐藏所有下一个tr td直到下一个tr th,jquery,toggle,show-hide,Jquery,Toggle,Show Hide,它应该很简单,但是这个jQuery函数占用了很多元素,我认为它甚至隐藏了jQuery 我想做的是,当一个人点击一个tr th时,所有下一个tr td应该隐藏到下一个tr th 我怎样才能让这个代码工作 <!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-latest.js"></script> <style> th
<!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>
背景:爸爸;
字体大小:粗体;
字体大小:16px;
宽度:50%;
}
背景:红色;
字体大小:粗体;
字体大小:16px;
宽度:50%;
}
展示它3
测试1
测试2
展示它2
测试3
测试4
$('#示例tr th')。单击(函数(){
//警报($(this.parent().html())
$(this.parent().nextUntil('tr th').toggle();
})
您可以向具有th
元素的tr
元素添加一个类:
<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>
这里有一种主要使用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;
}
});
$(“#示例tr td按钮”)。在('click',函数(e)上{
var sides=$(this.sides();
对于(变量i=0;i<1.length;i++){
if(兄弟[i].find('td').length)$(兄弟[i]).hide();
else if(兄弟[i].find('tr').length)返回;
}
});
谢谢。我用你的解决方案,因为它是如此简单。
$('#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;
}
});