Problem with adding and removing classes with jQuery when hovering over a list item
I want to add a class to a list item when I hover over it, and then remove it and add it to a different list item if a different list item is hovered over.
Here's what I tried:
jQuery -
$(document).ready(function() {
$("#results").text("Tournaments");
$("#Tournaments").addClass("box-active");
$("#box ul li").hover(function() {
var show = $(this).attr('id');
$("#results").text(show);
$("#box ul li").each(function() {
$(this).removeClass("box-active");
});
$("#box ul li#" + show).addClass("box-active");
});
});
HTML -
<div id="box">
<ul>
<li id="Tournaments">Tournaments</li>
<li id="Join">Join</li>
<li id="Forums">Forums</li>
<li id="GameBattles">GameBattles</li>
<li id="Practice">Practice</li>
</ul>
<p>Hovering over: <span id="results"></span></p>
</div>
When I hover over an item, it changes the开发者_开发问答 class, but if I hover over I different one it removes the class over the item I first hovered over, but doesn't add the class to the new item I'm hovering over. Not sure why, and any help would be appreciated.
I think the answer to this question may help.
Could be something like this:
$('#box ul li').hover( function(){
$(this).addClass('box-active');
$("#results").text($(this).attr('id'));
},
function(){
$(this).removeClass('box-active');
$("#results").text('');
});
EDIT: this will remove the class when you stop hovering over the li, not sure if that's your desired functionality or not
For one, no reason to put multiple id tags in a search try:
$("li#" + show).addClass("box-active");
but even better, since you are in the li itself:
$(this).addClass('box-active');
I'm not sure if this will work, but try this:
$(document).ready(function() {
$("#results").text("Tournaments");
$("#Tournaments").addClass("box-active");
$("#box ul li").hover(function() {
$("#results").text( $(this).attr('id') );
$("#box ul li.box-active").removeClass('box-active');
$(this).addClass('box-active');
});
});
精彩评论