问题
i have a button that is created dynamically so i need to use .live on my code. Here's an example:
$('#send').live('click', function(){
.....
..... code .....
.....
});
I'm using jQuery library 1.7.1 and i wanted to change it to using .on but it does not work. Why is this? Is the syntax different?
I looked at the documentation and I dont seem to be doing anything wrong. I dont mind leaving it like live but i would like to know if I'm doing something wrong.
http://api.jquery.com/on/
回答1:
Is the syntax different? Yes. Did you read all of the .on()
doco page you linked to?
The following summary about how to switch from .live()
to .delegate()
or .on()
is from the .live() doco page:
$(selector).live(events, data, handler); // jQuery 1.3+
$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+
$(document).on(events, selector, data, handler); // jQuery 1.7+
So in your case you want:
$(document).on('click', '#send', function(){
// your code here
});
Note though that ideally you won't be using $(document)
, you'll be using $(someotherelement)
to attach the handler to an element closer to your '#send' element. If you can, use whatever the direct parent element of '#send' is, or if the parent is dynamically created too use its parent.
回答2:
To use event delegation, .on
requires two selectors, like .delegate
.
$('some container').on('click', '#send', function() { ... });
来源:https://stackoverflow.com/questions/8650696/jquery-on-does-not-work-but-live-does-using-1-7-1-library