简体   繁体   English

如何从多个活动 li 中删除活动类(多选 li)

[英]How to remove class active from multiple active li (multiselect li)

I created an <ul> <li> list.我创建了一个<ul> <li>列表。 When you select each <li> , there will be active classes each.当您选择每个<li> ,每个都会有活动类。 Now, my goal is how to deselect or remove the active class on the current selected <li> if it has active class already.现在,我的目标是如何取消选择或删除当前所选<li>上的活动类(如果它已经有活动类)。

 $('.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 foo 1 and foo2 .现在,如果我想取消选择foo3而不删除foo 1 和foo2的活动类。 How can I do it?我该怎么做?

In this event, it only select and deselect one <li> at a time.在这种情况下,它一次只选择和取消选择一个<li> 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> .我想要的是我可以多选<li>或在它们上面放置活动类,并且可以取消选择一个<li>而不会影响其他<li>

actual code实际代码

For you desire result you just need toggleClass instead of remove and addClass .对于您想要的结果,您只需要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>

I hope this will help.我希望这将有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM