I want to create a super simple set of handlers for the hover() shortcut but i keep failing. I ultimately just went with mo开发者_如何学运维useenter/mouseleave but I want to see what my problem is here for future purposes.
$function(){
$('div.profile').find('li:gt(0)').each(function(){
this.hover(highlight,offlight);
});
});
var highlight=function(){
$(this).css("background","blue");
}
var offlight=function(){
$(this).css("background","none");
}
Ok so this is probably riddled with errors. First, I'm not sure if the "this" function context works in the second two functions definitions since this is not really defined outside of the ready handler. If it doesn't work, can I do anything else here to make sure that the "li" which gets highlighted is the same one is hovered over? Should I just make highlight and offlight anonymous functions or is there another way?
2) It seems as though my hover event handler fails no matter what I do. I think that I'm using the each function correctly here. I don't know what gives.
You're calling .hover()
on a DOM element. Call it on a jQuery object instead.
//-----v------was missing the "("
$(function() {
$('div.profile').find('li:gt(0)').hover(highlight,offlight);
});
// attach .hover() to all the <li> found-------^
As you can see, there's no need for the .each()
.
Overall, I'd use the CSS :hover
pseudo selector if all you're doing is a simple background change:
$(function() {
$('div.profile').find('li:gt(0)').addClass( "hoverMe" );
});
css
li.hoverMe {
background:none;
}
li.hoverMe:hover {
background:blue;
}
Won't work in IE6
without some tweaks to your markup though.
In your each
function, this
does not reference a jQuery object. You need to wrap it in $()
:
$(this).hover(highlight,offlight);
精彩评论