How do you add a current class to a li with jquery?
I have the following code:
<ul>
<li class="tree">
<span><a class="collapse" href="#">Collapse</a></span>
</li>
<li class="tree">
&开发者_开发百科lt;span><a class="expand" href="#">Expand</a></span>
</li>
</ul>
How can I add a class on the li to current when you click on the expand link and then take off the current when I click on the collapse in jquery?
$('.collapse').click(function(e){
$(this).closest('li').removeClass('current');
});
$('.expand').click(function(e){
$(this).closest('li').addClass('current');
});
if you need to stop the anchor going to the link, use:
e.preventDefault()
before the class add/removal.
adding class
$(".expand").click(function(){
$(this).closest('li').addClass('current');
});
removing class
$(".collapse").click(function(){
$(this).closest('li').removeClass('current');
});
$(".expand").click( function() {
$(this).closest('li').addClass('current');
});
$(".collapse").click( function() {
$(this).closest('li').removeClass('current');
});
@rob waminal More information can be found, http://api.jquery.com/closest/
精彩评论