Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

javascript - adding and remove classes on click events

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

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

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...