问题
Possible Duplicate:
jQuery 1.7 - Turning live() into on()
Just switching my code from "live" to "on" and some events just don't fire any more, here is an example, can anyone pls help out saying what's wrong with it? It WORKED 100% correct with "live" instead of "on" method before....
$('a#doBulkLink').on('click', function (e) {
createLabelsWithDestinationFolders();
$('label.moveDocDestinationFolder').on('click', function (e) {
doSomeAjaxStuffWithLabels();
e.stopImmediatePropagation();
});
e.preventDefault();
});
Thank You.
回答1:
You cannot replace live()
with on()
simply by changing the function name to on()
; the signature changes as well.
$('selector').live('event', function () {
});
... becomes ....
$(document).on('event', 'selector', function () {
});
In it's current form, what you have is a direct replacement for bind()
(of which click()
, change()
etc are aliases). As such, the handler is been bound directly to the element, rather than binding the handler to the document
and taking advantage of event bubbling, which is what live()
did.
回答2:
To use on()
in the same manner as live()
, do it as such:
$(document).on('click', 'a#doBulkLink', function() { } );
As indicated in the docs here: http://api.jquery.com/live/
回答3:
The way you have defined .on
will not work if a#doBulkLink
is inserted dynamically to the dom,
Try,
//replace document with any closest container of 'a#doBulkLink' which is available
//in dom when this code is executed.
$(document).on ('click', 'a#doBulkLink', function () {
createLabelsWithDestinationFolders();
$('label.moveDocDestinationFolder').on('click', function (e) {
doSomeAjaxStuffWithLabels();
e.stopImmediatePropagation();
});
e.preventDefault();
});
回答4:
I got it working, FIXED!!!!, I made 2 silly mistakes:
- First event (on a#doBulkLink) is not dynamic (It was on the hidden element that exists on a page, and that#s what tricked me!)
- In second event (on label.moveDocDestinationFolder) I used
$('document')
instead of$(document)
in my JQuery ".on" method syntax,
So the code looks like this and it's working WELL in 100%:
// this is not dynamically added element, but still can use ".on" to attach an event to
// outer div and delegate to a#doBulkLink when clicked
$('div#doBulkLinkBox').on('click', 'a#doBulkLink' ,function (e) {
createLabelsWithDestinationFolders();
// these are dynamic elements so let's use "on" to attach a click event
$(document).on('click', 'label.moveDocDestinationFolder', function (e) {
doSomeAjaxFunkWithLabels();
e.stopImmediatePropagation();
});
e.preventDefault();
});
THANKS to everyone for tips!!
来源:https://stackoverflow.com/questions/9892616/jquery-switching-application-from-live-to-on-method