I have this script that highlight the nav menu when clicked but after the click the selected class disappears. Is there a workaround in here to make the selected class in effect after the clicked?
<script type="text/javascript">
$( document ).ready( function() {
$( '#nav ul li a' ).click( function() {
$( '#nav ul li' ).removeClass( 'selected' );
$( this ).parent( 'li' ).addClass( 'selected' );
alert('hello');
});
});
</script>
<div id="nav">
<ul>
<li><a href="/">Home</a></li>
<li><a href="/blog/">Blog</a><开发者_如何转开发/li>
<li><a href="/about/">About</a></li>
</ul>
</div>
You can use the .siblings
method to get the li
elements which have the selected
class.
$( document ).ready( function() {
$( "#nav ul li a" ).click( function() {
$( this ).parent( "li" )
.addClass( "selected" )
.siblings( ".selected" )
.removeClass( "selected" );
return false;
});
});
You can see this in action on jsFiddle.
If i understand you correctly... Example: http://jsfiddle.net/jgmgW/
$( document ).ready( function() {
$( '#nav ul li' ).click( function() {
$( '#nav ul' ).children('li').removeClass();
$( this ).addClass( 'selected' );
});
});
#nav .selected a{background:red;display:block}
<div id="nav">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">Blog</a></li>
<li><a href="#">About</a></li>
</ul>
</div>
精彩评论