How to toggle a specific class set

天大地大妈咪最大 提交于 2019-12-12 03:56:09

问题


I have a range of classes:

  • classA
  • classB
  • classC

and I have a <span class='fixedClass'> which needs to be toggled between one of these classes depending on a specific condition. You might say to use jQuery toggleClass

However my span has already other class attached to it which needs to stay always.

What's fastest and shortest code in jQuery to do this?


回答1:


This sample may help you: http://jsfiddle.net/e9bj5/

$(function(){

 $('.fixedClass').on("click", function() {

    var box = $(this);

    if ( box.hasClass('red') ) {
        box.removeClass('red').addClass('green');
    }
    else if ( box.hasClass('green') ) {
        box.removeClass('green').addClass('blue');
    }
    else if ( box.hasClass('blue') ) {
        box.removeClass('blue').addClass('red');
    }

 });
});



回答2:


Can't you just go for changing the attribute "class" of your span, with .attr() Check below code

function(newClassName){
$('.fixedClass').attr('class',newClassName +' fixedClass');
}


来源:https://stackoverflow.com/questions/14684627/how-to-toggle-a-specific-class-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!