1.7+中的jQuery live()vs on() [英] jQuery live() vs on() in 1.7+

查看:61
本文介绍了1.7+中的jQuery live()vs on()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道从jQuery 1.7开始,不赞成使用.live()方法.这就是我想出的:

I know as of jQuery 1.7, the .live() method is deprecated. So this is what I came up with:

$(document.body).on('click', '#list', function() {
    console.log($(this));
});

几乎可以做到这一点,并且等同于:

Which pretty much does the trick and is equivalent to:

$('#list').live('click', function(){
    console.log($(this));
});

它们都返回 #list jQuery对象,这正是我想要的. 但是问题是当我将jQuery对象作为第二个参数而不是字符串(这很常见)时,例如:

They both return the #list jQuery object, which is what I wanted. The problem is however when I pass a jQuery object as a second parameter, instead of string (which happens quite often), eg:

var list = $('#list');
$(document.body).on('click', list, function() {
    console.log($(this));
});

控制台返回 $(body) jQuery对象.在这一点上,这是没有用的. ;) 有什么想法吗?

The console returns $(body) jQuery object. Which is useless in that point. ;) Any ideas?

这里的问题是如何从示例1和2访问受影响的对象$('#list'),但是如何在示例3中访问它.

The problem here is NOT how to access the affected object $('#list') from example 1 and 2, but how to access it in example 3.

推荐答案

在官方 docs :

不再建议使用.live()方法,因为稍后 jQuery版本提供了更好的方法,没有 缺点.特别是,使用 .live():

Use of the .live() method is no longer recommended since later versions of jQuery offer better methods that do not have its drawbacks. In particular, the following issues arise with the use of .live():

  • jQuery尝试在调用.live()方法之前检索选择器指定的元素,该方法可能是 在大型文档上很耗时.
  • 不支持链接方法.例如,$("a").find(".offsite, .external").live( ... ); 无效有效,并且无法按预期工作.
  • 由于所有.live()事件都附加在document元素上,因此事件花费的时间最长,最慢 处理之前的可能路径.
  • 调用 event.stopPropagation() 在事件处理程序中无法有效地停止事件处理程序 附在文件的下方;该事件已经传播到 document.
  • .live()方法与其他事件方法以令人惊讶的方式进行交互,例如, $(document).unbind("click")删除所有点击处理程序 通过任何呼叫附加到.live()
  • jQuery attempts to retrieve the elements specified by the selector before calling the .live() method, which may be time-consuming on large documents.
  • Chaining methods is not supported. For example, $("a").find(".offsite, .external").live( ... ); is not valid and does not work as expected.
  • Since all .live() events are attached at the document element, events take the longest and slowest possible path before they are handled.
  • Calling event.stopPropagation() in the event handler is ineffective in stopping event handlers attached lower in the document; the event has already propagated to document.
  • The .live() method interacts with other event methods in ways that can be surprising, e.g., $(document).unbind("click") removes all click handlers attached by any call to .live()!

这篇关于1.7+中的jQuery live()vs on()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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