jQuery live() vs on() in 1.7+

ε祈祈猫儿з 提交于 2019-12-30 10:49:10

问题


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));
});

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));
});

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

EDIT: 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.


回答1:


A pretty clear answer you will find in the official 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()!



回答2:


It's simply incorrect to pass an object as the second parameter to on.

From the docs:

.on( events [, selector] [, data], handler(eventObject) )

It asks for a selector and not a jQuery object, so you need to use:

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


来源:https://stackoverflow.com/questions/11686326/jquery-live-vs-on-in-1-7

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!