在jQuery 1.4.2中的一个现有的.hover方法的等效 [英] .delegate equivalent of an existing .hover method in jQuery 1.4.2

查看:111
本文介绍了在jQuery 1.4.2中的一个现有的.hover方法的等效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个事件处理程序使用.hover方法绑定到hover事件,如下所示:

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");
});

重要的是要注意,我需要处理程序中的两个函数来确保同步。是否可以使用.delegate重写函数,因为以下不起作用?

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

推荐答案

尝试这种方法:

Try this approach:

$(".nav").delegate("li", "hover", function () {
    $(this).toggleClass("hover");
});

这取决于 .nav 没有被替换通过AJAX或其他方式,因为这是事件处理程序生活的地方。如果被替换,您必须将代理附加在较高的祖先,而不是更换。

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.

还有一个小修正 $(。nav li)。hover(function(){不使用 .live()这将是: $(。nav li)。live('hover',function(){ .hover()将事件直接绑定到该代码运行时的元素...任何未来的元素都不会触发悬停代码,这就是 .live() .delegate()不同,他们通过冒泡在未来的元素上工作。

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.

这篇关于在jQuery 1.4.2中的一个现有的.hover方法的等效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆