javascript - 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 foo
1 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>
.
解决方案
对于您想要的结果,您只需要toggleClass而不是remove和addClass。
$('.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>
我希望这将有所帮助。
推荐阅读
- nlp - 什么是结合了符号和统计 NLP 直觉的自然语言 P,以便它可以自动纠正拼写错误同音异义词
- html - CSS :before 伪元素未显示为一个 h1
- node.js - 访问节点http服务器计算的header值
- ios - 更新 CoreML 模型时 MLUpdateContext 为空
- r - 使用mutate和lag,得到想要变成0的负值
- amazon-web-services - 使用 cloudformation 获取 ASG 中实例的可用区
- python - 从开始日期到结束日期按日期存储的多个 csv 文件读取到熊猫数据框中
- python - 使用 Flask 操作 HTML 元素的值
- python - 检查不同的列是否为空
- php - PHP Curl - SSL 对等点收到的证书有一些未指定的问题