gpt4 book ai didi

1.7+ 中的 jQuery live() 与 on()

转载 作者:行者123 更新时间:2023-12-01 01:09:15 24 4
gpt4 key购买 nike

我知道从 jQuery 1.7 开始,.live() 方法已被弃用。这就是我想到的:

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

这几乎可以达到目的并且相当于:

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

它们都返回 #list jQuery 对象,这就是我想要的。然而问题是当我传递一个 jQuery 对象作为第二个参数而不是字符串(这种情况经常发生)时,例如:

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

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

编辑:这里的问题不是如何访问示例 1 和 2 中受影响的对象 $('#list'),而是如何在示例 3 中访问它。

最佳答案

官方 docs 中有一个非常明确的答案:

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 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() 与 on(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11686326/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com