首页 > 解决方案 > How to remove class active from multiple active li (multiselect li)

问题描述

I created an <ul> <li> list. When you select each <li>, there will be active classes each. Now, my goal is how to deselect or remove the active class on the current selected <li> if it has active class already.

$('.package_wrap li').click(function() {
    $('.package_wrap li.active').removeClass('active');
    $(this).addClass('active');
});
.active {
    background-color: lightgreen;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="package_wrap">
    <li class="active">foo1</li>
    <li class="active">foo2</li>
    <li class="active">foo3</li>
    <li>foo4</li>
    <li>foo5</li>
</ul>

Now, if I want to deselect foo3 without removing the active class of foo1 and foo2. How can I do it?

In this event, it only select and deselect one <li> at a time. What I want is that I can multi select <li> or put active classes on them and can deselect one <li> without affecting other <li>.

actual code

标签: javascriptjquery

解决方案


对于您想要的结果,您只需要toggleClass而不是removeaddClass

$('.package_wrap li').click(function() {
    $(this).toggleClass('active');
});
.active {
    background-color: lightgreen;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="package_wrap">
    <li class="active">foo1</li>
    <li class="active">foo2</li>
    <li class="active">foo3</li>
    <li>foo4</li>
    <li>foo5</li>
</ul>

我希望这将有所帮助。


推荐阅读