adding and remove classes on click events

2019-09-24 01:54发布

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/

4条回答
劫难
2楼-- · 2019-09-24 02:09
var li = $('.child-item');
li.click(function(){
  li.removeClass('active');
  $(this).toggleClass('active');
});
查看更多
smile是对你的礼貌
3楼-- · 2019-09-24 02:28

.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

查看更多
来,给爷笑一个
4楼-- · 2019-09-24 02:29

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/

查看更多
姐就是有狂的资本
5楼-- · 2019-09-24 02:33

Try it also :

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

FIDDLE DEMO

查看更多
登录 后发表回答