javascript - remove active class on the next element
问题描述
I'm working on this selection which adds active class, what I want is to remove the active class next to the selected element. If there's only one option left. ex. I got 5 options, then selected 1,2,3,4 if I select the fifth option the active class of the first option will be remove, then If I select again the 1 it will become active then, option 2 will become inactive.
Hope you help me. thanks.
$('ul li a').click(function() {
$(this).addClass('active');
var len = $('ul .active').length;
var arr = [];
$('ul li a').each(function(i) {
if ($(this).hasClass('active')) {
arr.push(i + 1);
if (len > 4) {
if (arr[arr.length - 1] == 5) {
$('ul li:nth-child(' + arr[0] + ') a').removeClass('active');
}
}
}
});
});
ul{
padding: 0;
}
ul li{
float: left;
list-style-type: none;
}
ul li a{
text-decoration: none;
color: #333;
padding: 10px 15px;
background-color: #DDD;
margin: 5px;
border-radius: 100px;
}
ul li a.active{
background-color: green;
color: #FFF;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">4</a></li>
<li><a href="#">5</a></li>
</ul>
解决方案
You can try something like this, Check if next li
exist and add logic
$('ul li a:not("active")').click(function() {
$(this).parent().next("li").find("a").removeClass("active");
if ($(this).parent().next("li").length == 0)
{
$('ul li a').eq(0).removeClass("active");
}
$(this).addClass("active");
});
ul{
padding: 0;
}
ul li{
float: left;
list-style-type: none;
}
ul li a{
text-decoration: none;
color: #333;
padding: 10px 15px;
background-color: #DDD;
margin: 5px;
border-radius: 100px;
}
ul li a.active{
background-color: green;
color: #FFF;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">4</a></li>
<li><a href="#">5</a></li>
</ul>
推荐阅读
- python - 在python中导入sklearn
- javascript - jquery 添加/删除可排序的 div 和更新计数
- wordpress - Woocommerce 禁用特定产品 ID 的评论
- javascript - 配置 eslint 和 jslint 以不使用保留的 react-native 关键字(如 [import,export])给出错误
- javascript - 一个列表项而不是所有列表项的 ReactJS 悬停/鼠标悬停效果
- delphi - Delphi:在移动应用程序的运行时创建一个 TListItemTextButton
- mosquitto - Mosquitto SSL 连接被拒绝
- wmi - WMI 向用户查询 SID
- .net - 使用 .NET 缩小 json 字符串
- c# - 页面加载后动态创建的按钮重新加载页面但不会触发