简体   繁体   中英

Active class not working properly

I have some menu items and in the menu I have a plus(+) sign. When I click on the plus sign it should add a class and look like cross. It is happening but when I click the cross sign it does not removing the sign so that I can get the plus sign again.

$(document).ready(function(){    
  $('.nav-link').click(function(){
    $('.nav-link').removeClass('addplus');
    $(this).addClass('addplus');
  });

});

Here is the Example .

The issue is because you are always removing, then immediately adding the class back on the clicked element. To fix this exclude the current element from the removeClass() call using not() , then use toggleClass() to add/remove the class to the required element, like this:

$('.nav-link').click(function() {
  $('.nav-link').not(this).removeClass('addplus');
  $(this).toggleClass('addplus');
});

Updated fiddle

I've gone a bit around about the houses here, but this works using parent and siblings :

$('.nav-link').click(function() {
    $(this).parent(".nav-item").siblings().children(".nav-link").removeClass('addplus');
    $(this).toggleClass('addplus');
});

I wouldn't do a blanket removeClass across all matching elements like you've done, I'd pick them out by excluding the currently matched element. Revised fiddle: https://jsfiddle.net/epqxb6L7/5/

It's because your code is removing and adding the same class every time click event triggers. Try something like this

$(document).ready(function(){    
   $('.nav-link').click(function(){
   $(this).toggleClass('addplus'); //THIS WILL ADD/REMOVE CLASS ALTERNATIVELY
  });
});

You always add the class addplus in the last line of your click handler. Try the following instead:

$(document).ready(function(){    
  $('.nav-link').click(function(){
    if ($(this).hasClass('addplus')) {
      $(this).removeClass('addplus');
    } else {
      $(this).addClass('addplus');
    }
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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