.delegate equivalent of an existing .hover method in jQuery 1.4.2

こ雲淡風輕ζ 提交于 2019-12-11 12:59:22

问题


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 () {
    $(this).removeClass("hover");
});

Rich


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/2591885/delegate-equivalent-of-an-existing-hover-method-in-jquery-1-4-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!