.delegate equivalent of an existing .hover method in jQuery 1.4.2
I have an event handler bound to the hover event using the .hover method, which is below:
$(".nav li").hover(function () {
$(this).addClass("hover");
}, function () {
$(this).removeClass("hover");
});
It is important to note, that I require both functions within the handler to ensure synchronisation. Is it possible to rewrite the function using .delegate, as the following does not work?
$(".nav").delegate("li", "hover", function () {
$(this).addClass("hover");
}, function () {
$(开发者_Go百科this).removeClass("hover");
});
Rich
Try this approach:
$(".nav").delegate("li", "hover", function () {
$(this).toggleClass("hover");
});
This depends on .nav
not getting replaced via AJAX or otherwise though, since that's where the event handler lives. If it is being replaced, you have to attach the delegate on a higher ancestor that's not getting replaced.
Also a minor correction, $(".nav li").hover(function () {
isn't using the .live()
method, that would be: $(".nav li").live('hover', function () {
. .hover()
binds the event directly to the element when that code runs...any future elements wouldn't trigger that hover code, that's where .live()
and .delegate()
differ, they work on future elements via bubbling.
To add/remove a class Nick's solution is perfect as jQuery provides the appropriate toggleClass method.
If you need to trigger more complex functions that do not have a corresponding toggle method available, you can do that by testing the event type:
$(".nav").delegate("li", "hover", function (event) {
if(event.type == "mouseenter"){
$(this).find(".subDiv").slideDown();
}else{
$(this).find(".subDiv").slideUp();
}
});
This will work for jQuery >=1.4.3 - for older versions use mouseover instead of mouseenter.
精彩评论