问题
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