问题
i have any navigation menu !
<div class="nav">
<ul class="navigation">
<li class="selected"><a href="#">HOME</a></li>
<li><a href="#">PROFILE></a></li>
<li><a href="#">CONTACTUS</a></li>
<li><a href="#">ABOATUS</a></li>
</ul>
</div>
Now how to add selected class after click to any ( profile, Contactus, aboutus ) and remove selected home using Jquery.
Thanks
回答1:
On the assumption that you want to have only one element of class-name selected
I suggest:
$('ul.navigation li a').click(
function(e) {
e.preventDefault(); // prevent the default action
e.stopPropagation(); // stop the click from bubbling
$(this).closest('ul').find('.selected').removeClass('selected');
$(this).parent().addClass('selected');
});
JS Fiddle demo.
回答2:
you can use toggleClass:
$("#myElement1").click(function(){
$("#myElement2").toggleClass("myClass");
});
回答3:
$("a").click(function()
{
$("a").parent().removeClass("selected");
$(this).parent().addClass("selected");
});
Live Demo
来源:https://stackoverflow.com/questions/7138021/jquery-add-remove-class-onclick