Jquery ToggleClass widthout separating the class names
<script type="text/javascript">
$(document).ready(function(){
$("input").click(function(){
$(".ABC").toggleClass("else");
});
});
</script>
<body>
<p class="ABC">hahahahhaha</p>
<input type="button" value="click" />
</body>
Runing the above code, the class of <p>
will be switched between "ABC else" and "ABC" by button clicking.
For example:
1st click: <p class="ABC">
become <p class="ABC else">
2nd click: <p class="ABC else">
become <p class="ABC">
However, I want the classname to be swiched between "ABC" and "ABCelse" (NO SPACE BETWEEN ABC AND ELSE). Is there a way to solve this problem? Thanks in advance.
You can do something like this, toggle the ABC class separately from ABCelse.
$(this).find(".ABC").toggleClass("ABC").toggleClass("ABCelse");
$(":button").click(function(){
$("div").toggleClass(function(){
if($(this).is(".ABC")){return "else";}
else if($(this).is(".else")){return "ABC";}
});
});
here is the fiddle http://jsfiddle.net/DgAPR/
First of all, the reason there is a space between them is because .toggle() is adding the class 'else' to the div. So it now has two classes: .ABC & .else
What you want to do is actually REMOVE the class .ABC and add the class .ABCelse, OR remove the class .ABCelse and add the class .ABC:
$('button').click(function(){
$(this).find('.ABC').removeClass('ABC').addClass('ABCelse');
$(this).find('.ABCelse').removeClass('ABCelse').addClass('ABC');
});
精彩评论