jQuery的区别.live和jQuery.delegate

difference between jQuery.live and jQuery.delegate

本文关键字:jQuery delegate 区别 live      更新时间:2023-09-26

我读过一些关于为什么不使用jQuery.live()的帖子,我想检查一下我是否得到了它:)当我调用$("body").delegate('element','click', function);

$(element).live('click', function)相同吗?在正常行为的情况下,根据帖子,有一些stopPropagation和性能的好处,但主要的区别是live绑定每次到body元素,而delegate可以绑定到另一个?

一个重要的区别是,".live()"实际上会为初始选择器构建jQuery元素列表,尽管".live()"函数本身只需要选择器字符串。这意味着,如果选择器有点昂贵,那么设置处理程序的代码将毫无理由地在整个DOM上运行。".delegate()"调用而不是

我真的看不出新代码应该使用".live()"的任何理由;这是一个架构上的错误,最终应该安静地死去。

Nettuts有一个屏幕视频来解释这一点:快速提示:Live()和Delegate()之间的区别

引自网站:

// Live(), introduced in 1.3, allows for the binding  
// of event handlers to all elements that match a  
// selector, including those created in the future.  
// It does this by attaching the handler to the document.  
// Unfortunately, it does not work well with chaining.  
// Don't expect to chain live() after calls like  
// children().next()...etc.  
$("li").live("click", function() {  
    $(this).parent().append("<li>New Element</li>");  
});   
// Delegate, new to version 1.4, perhaps should have been a complete  
// replacement for Live(). However, that obviously  
// would have broken a lot of code! Nonetheless,  
// delegate remedies many of the short-comings  
// found in live(). It attaches the event handler  
// directly to the context, rather than the document.  
// It also doesn't suffer from the chaining issues  
// that live does. There are many performance benefits  
// to using this method over live().  
$('#items').delegate('li', 'click', function() {  
    $(this).parent().append('<li>New Element</li>');  
});   

是live绑定每次都绑定到body元素的主要区别,而delegate可以绑定到另一个?

是的,没错。假设您有一个表,您要从中添加和删除行,并且您希望处理对这些行(或行内的链接或按钮)的单击。你可以使用live来实现这一点,但随后事件必须一直向下冒泡到身体水平,让我们面对它,它感觉有点像一个全局变量。如果在table元素上使用delegate,则可以保持更有针对性,与页面上发生的其他事情隔离开来。delegatelive的一个更模块化的包含版本。

由于.live()方法在事件传播到文档顶部时处理事件,因此不可能停止活动事件的传播。类似地,.delegate()处理的事件将始终传播到它们被委托的元素;在调用委托事件处理程序时,它下面任何元素的事件处理程序都已经执行。

简而言之,.live在文档级别运行,而.delegate在您指定的任何元素上运行。为什么会有不同呢?如果您使用.live绑定了一个(或多个)mousemove事件,jQuery将在每次将鼠标移动到页面上的任何位置时执行代码,以查看回调函数是否应该运行。这是非常低效的,这就是使用.delegate的原因。.delegate函数只在您指定的dom节点内部产生偶数时运行。例如,如果您说的是$('ul#myUL').delegate(...),那么jQuery只会在事件源自ul#myUL

时检查代码是否应该运行。