Jquery toggle multiple buttons

2019-04-07 15:49发布

I have multiple buttons, that get their active css style with a jquery toggle script. But I want to have only one button at a time active. But also, when I re-click an active button, it has to become unactive.

$(document).ready(function(){
    $('.button').click(function() {       
        $(this).toggleClass('buttonactive');
    });
});

Basicly I need to add a line saying:

$(all .button except this).removeClass('buttonactive');

I don't know how. Can someone help me? Here's a JSFIDDLE with the problem: http://jsfiddle.net/nV5Tu/3/

标签: jquery toggle
4条回答
贼婆χ
2楼-- · 2019-04-07 16:33

Why dont you simply remove for all and just add for this ?

$('.button').click(function() {       
    $('.button').removeClass('buttonactive');    
    $(this).addClass('buttonactive');
});
查看更多
女痞
3楼-- · 2019-04-07 16:35

This should do the trick:

$(document).ready(function(){
    $('.button').click(function() {
        if($(this).hasClass("buttonactive")) {       
            $(this).removeClass('buttonactive');
        } else {
            $(this).addClass('buttonactive');
        }
        $(".button").removeClass("buttonactive"); // removes all other active classes
    });
});
查看更多
4楼-- · 2019-04-07 16:41

You can do it like this using .toggleClass() to toggle current element.. then using .not() to filter out current element from having class removed

$('.button').click(function() {  
    $('.button').not(this).removeClass('buttonactive'); // remove buttonactive from the others
    $(this).toggleClass('buttonactive'); // toggle current clicked element
});

FIDDLE

查看更多
Melony?
5楼-- · 2019-04-07 16:48

you don't need three document.ready(function().. one is enough ...

$('.button').click(function() { 
 $(".button").removeClass("buttonactive");  // remove the class for all button on click
});

fiddle here

查看更多
登录 后发表回答