问题
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/
回答1:
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/
回答2:
.toggle() (Event) - is deprecated in jQuery 1.8 and removed in jQuery 1.9
Use add()
with toggleClass()
on .active
<li>
$('.child-item').click(function(e){
$('li.child-item.active').add(this).toggleClass('active');
});
Updated Fiddle
回答3:
var li = $('.child-item');
li.click(function(){
li.removeClass('active');
$(this).toggleClass('active');
});
回答4:
Try it also :
$('.child-item').click(function(e){
$('.child-item.active').removeClass('active');
$(this).addClass('active');
});
FIDDLE DEMO
来源:https://stackoverflow.com/questions/30083731/adding-and-remove-classes-on-click-events