开发者

Toggle multiple element classes with jQuery

I need to be able to toggle class when I click an element. It works fine for that element:

$(".main").click(function() {
    $(this).toggleClass("classA"开发者_如何学编程).toggleClass("classB");
});

But I would like to add to it to toggle classes for all elements on the page that have a particular class, say "togToo". For those elements I need to toggle between "classC" and "classD".

I'm almost certain there's a way to combine that into one click...

^^^ UPDATED ABOVE ^^^


If the elements to be toggled start off with one of the two classes, you can then toggle back and forth like this:

$('#element_to_click').click( function(){
  $('.togToo').toggleClass('classC classD');
});


Answer Updated

$(".main").click(function() {
    $(this).toggleClass("classA").toggleClass("classB");
    $('.togToo').toggleClass("classC").toggleClass("classD");
})


You can toggle N classes all at once

$(/* selector */).toggleClass('classA classB classC');


Why won't you use jQuery class selector?

$('.togToo').toggleClass("classC").toggleClass("classD");


This should do the trick:

$(".main").click(function() {
  $(this).toggleClass("classA").toggleClass("classB");
  $(".togToo").toggleClass("classC").toggleClass("classD");
));

Also, when toggling classes, i would suggest having a base class, and a toggle class, instead of toggling between two classes.


If you're looking for a way to toggle through mutliple classes one after each other and not all together I quickly wrote a little script you can use:

https://github.com/ThibaultJanBeyer/.toggleClasses-for-jQuery

it extends a new jQuery method .toggleClasses() that does exactly what you want. check it out and feel free to make it better if you have improvements :)


You can simply do something like

$(".classC").toggleClass("ClassD");

inside the "click" handler


I do it this way, having multiple images with class $('.img-polaroid') and class $('.drag'), when one of the images is clicked, it remove the $('.drag') to this element after having add it back to all of them

$('.img-polaroid').click(function(){
    if ($(this).hasClass('drag')) {
        $('.img-polaroid').addClass('drag');
        $(this).removeClass('drag');
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜