jQuery的区别.live和jQuery.delegate
difference between jQuery.live and jQuery.delegate
我读过一些关于为什么不使用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
,则可以保持更有针对性,与页面上发生的其他事情隔离开来。delegate
是live
的一个更模块化的包含版本。
由于.live()方法在事件传播到文档顶部时处理事件,因此不可能停止活动事件的传播。类似地,.delegate()处理的事件将始终传播到它们被委托的元素;在调用委托事件处理程序时,它下面任何元素的事件处理程序都已经执行。
简而言之,.live
在文档级别运行,而.delegate
在您指定的任何元素上运行。为什么会有不同呢?如果您使用.live
绑定了一个(或多个)mousemove事件,jQuery将在每次将鼠标移动到页面上的任何位置时执行代码,以查看回调函数是否应该运行。这是非常低效的,这就是使用.delegate
的原因。.delegate
函数只在您指定的dom节点内部产生偶数时运行。例如,如果您说的是$('ul#myUL').delegate(...)
,那么jQuery只会在事件源自ul#myUL
- 无法从 jQuery RSS Feed 中的 localStorage 动态替换类
- 如何使用jQuery自动打开页面上的所有链接
- 如何使用jquery在填充自动完成的值后使文本框只读
- 如何将bind()pass-through(to on())转换为delegate()-就像jQuery 1.7.1代码
- Devil of a time with jQuery delegate and .not
- jQuery .on() 和 .delegate() 在 iPad 上不起作用
- jQuery delegate()/on()-强制事件顺序
- live()、delegate()和on()在使用jQuery发出几次ajax请求后停止工作
- jQuery Delegate callback
- jQuery delegate and preventDefault()
- jQuery在.keypress()和.delegate()之后从动态创建的内容中获取值
- 为什么JQuery live()可以工作,而delegate()不能工作?
- Jquery delegate/live不起作用
- 在jQuery中,我应该选择live(), delegate()还是on()
- JQuery Delegate IE8
- JQuery已弃用的delegate()的替代方法是什么?
- 多个Jquery .delegate()问题
- jQuery delegate() 不适用于 $(this)
- 使用带有复选框的jQuery delegate (on)会导致巨大的响应延迟-为什么?
- jQuery的区别.live和jQuery.delegate