我已经阅读了一些关于为什么不使用 jQuery.live() 的帖子,我想检查一下我是否明白了:) 当我打电话时$("body").delegate('element','click', function);
是一样的$(element).live('click', function)
吗?在正常行为的情况下..根据帖子,有一些 stopPropagation 和性能好处,但主要区别是每次都绑定到 body 元素,而委托可以绑定到另一个?
我已经阅读了一些关于为什么不使用 jQuery.live() 的帖子,我想检查一下我是否明白了:) 当我打电话时$("body").delegate('element','click', function);
是一样的$(element).live('click', function)
吗?在正常行为的情况下..根据帖子,有一些 stopPropagation 和性能好处,但主要区别是每次都绑定到 body 元素,而委托可以绑定到另一个?
一个重要的区别是“.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
它,但是事件必须一直冒泡到身体水平,让我们面对现实吧,感觉有点像一个全局变量。如果您改为delegate
在table
元素上使用,您将保持更有针对性,与页面上发生的其他事情隔离开来。delegate
是一个更加模块化、包含的版本live
。
由于 .live() 方法在事件传播到文档顶部后处理事件,因此无法停止实时事件的传播。同样,由 .delegate() 处理的事件将始终传播到它们被委托的元素;在调用委托的事件处理程序时,它下面的任何元素上的事件处理程序都已经执行。
简而言之,它.live
在文档级别.delegate
运行并在您指定的任何元素上运行。为什么会有所作为?如果您使用 绑定了一个(或多个) mousemove 事件.live
,则每次您将鼠标移动到页面上的任何位置时,jQuery 都会执行代码以查看您的回调函数是否应该运行。这是非常低效的,也是拥有.delegate
. .delegate
仅当偶数起源于您指定的 dom 节点内部时,函数才会运行。例如,如果您说$('ul#myUL').delegate(...)
,那么 jQuery 只会检查代码是否应该在事件源自内部时运行ul#myUL