首页 > 解决方案 > 仅根据类切换某些元素

问题描述

我有一个简单的表:

<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() 但我没有得到它。

标签: javascriptjquerytoggle

解决方案


使用过滤器选择项目

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


推荐阅读