Reputation: 2149
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.
Upvotes: 3
Views: 313
Reputation: 26755
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));
});
Upvotes: 1
Reputation: 6529
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 thedocument
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 todocument
.- 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()
!
Upvotes: 3