Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am working on a click event, which intially is pretty standard.

on.click: Remove the active class from all list items, then add active to the clicked list item.

ie

var li = $('.child-item');
li.click(function(){
  li.removeClass('active');
  li.addClass('active');
});  

Works as expected. However, I also need a condition that if the active class is clicked again, it will remove the active class from the clicked item.

I tried this:

$('.child-item').toggle(function(e){
    
   $('.child-item').removeClass('active');
   $(this).addClass('active');

}, function() {
   $('.child-item').removeClass('active');
   $(this).removeClass('active');           
});    

but often the toggle is in the off state, so it requires a double click to get the toggle back on track. This seems like it would be a pretty straightforward solution, but I cannot seem to get it to work.

Added a jsFiddle here with another option. This is fine for when the same element is clicked, but it doesn't clear all active classes on each click.

Update

I got it working but TrueBlueAussie's answer is shorter and better. Here is my working fiddle: https://jsfiddle.net/v7b8cbj5/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
241 views
Welcome To Ask or Share your Answers For Others

1 Answer

Your second click handler will only attach to matching "active" items when the event was registered.

Replace it all with just this:

$('.child-item').click(function(e){
   $('.child-item.active').not(this).removeClass('active');    
    $(this).toggleClass('active');
});

You can use not() to exclude the current item from selected list of things to make inactive, then just toggle the selected one.

JSFiddle: https://jsfiddle.net/81ex7dmm/2/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...