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.
但是今天我将它绑定到docready之后的一个对象上(来自ajax a call)。这捆东西粘不住。
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?
我刚接触过jquery,感觉我漏掉了什么,这两种方法有什么区别吗?他们是什么?
Is this latter syntax the only way now to do bindings on new elements ( the purpose livequery plugin used to serve ) ?
后一种语法是现在对新元素进行绑定的唯一方法吗(livequery插件的用途)?
1 个解决方案
#1
14
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.
第二个示例将事件监听器绑定到文档对象。它将检查冒泡到文档对象的任何事件,并测试在触发函数之前,事件启动的元素是否与选择器匹配。当侦听器被绑定时,它不需要在文档中存在元素。事件可以被捕获(由另一个侦听器捕获),并且在它冒泡到文档对象之前停止传播。
#1
14
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.
第二个示例将事件监听器绑定到文档对象。它将检查冒泡到文档对象的任何事件,并测试在触发函数之前,事件启动的元素是否与选择器匹配。当侦听器被绑定时,它不需要在文档中存在元素。事件可以被捕获(由另一个侦听器捕获),并且在它冒泡到文档对象之前停止传播。