I'm trying to set a class for a li item, with 开发者_如何学Cno luck. I have tried many things (to much to post) but I can't figure it out:
$("li").live("mouseover",function(){
$(this).addClass('current');
});
The li item has to change class on mouseover(/hover) and keep that class state even if the mouse hovers outside the ul. But (and this is the tricky part) lose the class if another li item is hovered. Which means that the item being hovered gets the ''current'' class.
Hope it makes some sense..This is the fiddle jsfiddle
You should remove the class from all the elements that currently have it before adding it to the new element:
$("li").live("mouseover", function() {
$('.current').removeClass('current');
$(this).addClass('current');
});
jsFiddle
For added optimisation (i.e. to save the $('.current')
selection, which can be expensive in some older browsers), you could check to see if the element hovered already has the class:
$("li").live("mouseover", function() {
if (!$(this).hasClass('current')) {
$('.current').removeClass('current');
$(this).addClass('current');
}
});
Or, per Felix's excellent idea,
var current;
$("li").live("mouseover", function() {
if (this !== current) {
$(current).removeClass('current');
$(this).addClass('current');
current = this;
}
});
jsFiddle
Just remove the class from its siblings:
$("li").live("mouseover",function(){
$(this).addClass('current');
$(this).siblings().removeClass("current");
});
I've fixed it for you in the fiddle fiddle if you remove the current class from all the li elements and then apply it, you'll have better luck.
精彩评论