当前位置: 代码迷 >> JavaScript >> 仅基于类切换某些元素
  详细解决方案

仅基于类切换某些元素

热度:85   发布时间:2023-06-13 12:42:26.0

我有一个简单的表:

<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()玩了一段时间,但我没有。

使用过滤器选择项目

 $('.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> 

您可以填写的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> 

  相关解决方案