jquery on does not work but live does using 1.7.1

2020-06-12 03:54发布

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/

标签: jquery events
2条回答
狗以群分
2楼-- · 2020-06-12 04:33

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.

查看更多
可以哭但决不认输i
3楼-- · 2020-06-12 04:48

To use event delegation, .on requires two selectors, like .delegate.

$('some container').on('click', '#send', function() { ... });
查看更多
登录 后发表回答