简体   繁体   English

jQuery $(document).on('click',选择器,…)vs $(selector).on('click',

[英]jquery $(document).on('click', selector, … ) vs $(selector).on('click',

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 ). 但是今天,我将其绑定到docready之后(通过ajax调用)后出现的对象上。 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? 我从jquery休息了一下,觉得自己错过了一些东西,这2种方法是否有真正的区别? What are they? 这些是什么?

Is this latter syntax the only way now to do bindings on new elements ( the purpose livequery plugin used to serve ) ? 这后一种语法是现在对新元素(用于服务的目标livequery插件)进行绑定的唯一方法吗?

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. 它为每个元素添加一个单独的侦听器,并且只会响应添加侦听器时DOM中元素上的事件。

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. 在事件冒泡到文档对象之前,可能会捕获事件(由另一个侦听器)并停止传播。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM