Toggling between Menu Active states using jQuery
I have the following jQuery code:
$("ul.menu li a").click(function() {
$("ul.menu li a").removeClass("currentMenu");
$(this).addClass("currentMenu");
});
A开发者_如何转开发t page startup, my "Home" menu button is set to "currentMenu", which basically has a color background set to orange.
What I am trying to achieve, which the above jQuery code doesn't cater for is if I click on the existing "Home" button that is set to "currentMenu", I actually would like to remove this class, so the "Home" button no longer has the orange background color and vice-versa, when "Home" button unset, then set to "currentmenu" class.
You can do it using .not()
to filter out the current element then .toggleClass()
, like this:
$("ul.menu li a").click(function() {
$("ul.menu li a").not(this).removeClass("currentMenu");
$(this).toggleClass("currentMenu");
});
You can test it out here, this just filters the clicked anchor out of the collection so it won't be affected by the .removeClass()
then does .toggleClasss()
instead of .addClass()
to give the toggle on/off effect you're after.
Something like this might work:
$("ul.menu li a").click(function() {
if ($(this).is(".currentMenu")) {
$(this).removeClass("currentMenu");
} else {
$(this).addClass("currentMenu");
}
$("ul.menu li a").not(this).removeClass("currentMenu");
});
精彩评论