jQuery/javascript - Highlight for a menu when user click on it
Hi
Suppose I have a menu like:<ul>
<li><a href="xxx">notebook</a></li>
<li><a href="xxx">camera</a></li>
<li><a href="xxx">phone</a></li>
</ul>
When I click on a menu, the menu will be highlighted, if click on another menu, this menu will be highlighted and other menu will return to original(no hi开发者_如何学Pythonghlighted). Can someone give me some idea how to do it(create a listener for <li>
or anything else)?
The most efficient way would be via .delegate()
, like this:
$("ul").delegate("li", "click", function() {
$(this).addClass("active").siblings().removeClass("active");
});
Then just give it some styling to match, for example:
.active a { color: red; }
You can test it out here, if you want a click on an already-active <li>
to make it inactive, then change .addClass()
to .toggleClass()
, like this.
You didn't provide a lot to go on, but assuming that's the only unordered list on the page...
<script type="text/javascript">
$( document ).ready( function() {
$( 'ul li' ).click( function() {
$( 'ul li' ).removeClass( 'highlight' );
$( this ).addClass( 'highlight' );
});
});
</script>
So when any li gets clicked, the 'highlight' class (assuming there is one that does the highlighting of which you speak) gets removed from all of the li elements. Then the one that triggered the click gets the highlight class.
Might be better to have the 'a' element actually trigger the jquery, now that I think about it.
<script type="text/javascript">
$( document ).ready( function() {
$( 'ul li a' ).click( function() {
$( 'ul li' ).removeClass( 'highlight' );
$( this ).parent( 'li' ).addClass( 'highlight' );
});
});
</script>
That's the best I can do given the information that you've provided.
精彩评论