问题描述
我有一个简单的表:
<table>
<tr class="header">
<th>
....
</th>
</tr>
<tr class="level2">
<th>
....
</th>
</tr>
<tr class="level3">
<th>
....
</th>
</tr>
<tr class="level3">
<th>
....
</th>
</tr>
<tr class="level2">
<th>
....
</th>
</tr>
<tr class="level3">
<th>
....
</th>
</tr>
<tr class="level3">
<th>
....
</th>
</tr>
</table>
这非常有用,可以将所有内容从一个“标题”切换到下一个。
$('.header').click(function () {
$(this).nextUntil('tr.header').toggle();
});
但是我不知道该怎么做,就是只切换“ level2”类的元素,而将“ level3”隐藏起来。
我已经使用.toggleClass()和.netAll()玩了一段时间,但我没有。
1楼
使用过滤器选择项目
$('.header').click(function () { var trs = $(this).nextUntil('tr.header') trs.filter('.level2').toggle(); trs.filter('.level3').hide(); });
.header { background-color: green; } .level2 { background-color: yellow; } .level3 { background-color: blue; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr class="header"> <th> .... </th> </tr> <tr class="level2"> <th> .... </th> </tr> <tr class="level3"> <th> .... </th> </tr> <tr class="level3"> <th> .... </th> </tr> <tr class="level2"> <th> .... </th> </tr> <tr class="level3"> <th> .... </th> </tr> <tr class="level3"> <th> .... </th> </tr> </table>
2楼
您可以填写的filter
参数以仅选择所需的元素,在这种情况下:
$(this).nextUntil('tr.header', '.level2').toggle();
// ^^^^^^^^^
例:
$('.header').click(function () { $(this).nextUntil('tr.header', '.level2').toggle(); });
.header { background-color: green; } .level2 { background-color: yellow; } .level3 { background-color: blue; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr class="header"> <th> .... </th> </tr> <tr class="level2"> <th> .... </th> </tr> <tr class="level3"> <th> .... </th> </tr> <tr class="level3"> <th> .... </th> </tr> <tr class="level2"> <th> .... </th> </tr> <tr class="level3"> <th> .... </th> </tr> <tr class="level3"> <th> .... </th> </tr> </table>