首页 > 解决方案 > 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>

标签: javascriptjquery

解决方案


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>


推荐阅读