最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jquery $(document).on('click', selector, ... ) vs $(selector).on('click', - Stack O

programmeradmin0浏览0评论

I have always used in the past:

$(selector).on('click', function )

But today I was binding this on an object that came in after docready ( from ajax a call ). The binding would not stick.

After googling I saw this:

$(document).on( event, selector, function ) 

syntax. And after changing to this, my code was working.

I have been on a break from jquery and feel like I've missed something, are there a real differences in these 2 methods? What are they?

Is this latter syntax the only way now to do bindings on new elements ( the purpose livequery plugin used to serve ) ?

I have always used in the past:

$(selector).on('click', function )

But today I was binding this on an object that came in after docready ( from ajax a call ). The binding would not stick.

After googling I saw this:

$(document).on( event, selector, function ) 

syntax. And after changing to this, my code was working.

I have been on a break from jquery and feel like I've missed something, are there a real differences in these 2 methods? What are they?

Is this latter syntax the only way now to do bindings on new elements ( the purpose livequery plugin used to serve ) ?

Share Improve this question asked Nov 17, 2013 at 15:58 user854894user854894 3
  • 7 api.jquery.com/on That link will provide all the answers you could possibly need. – Rory McCrossan Commented Nov 17, 2013 at 15:59
  • 2 There are indeed real differences between the two, and they are thoroughly explained in the documentation – adeneo Commented Nov 17, 2013 at 16:00
  • 5 Particularly note the section on Direct and delegated events. – Jonathan Lonowski Commented Nov 17, 2013 at 16:00
Add a comment  | 

1 Answer 1

Reset to default 23

The first example binds the event listener directly to the elements. It adds a separate listener for each element, and it will only respond to events on elements that were in the DOM at the time the listeners were added.

The second example binds the event listener to the document object. It will check any event that bubbles up to the document object and test to see if the element the event started on matches the selector before firing the function. It doesn't require the elements to exist in the document when the listener is bound. It is possible for the event to be captured (by another listener) and propagation stopped before it bubbles up to the document object.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论