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

查看:103
本文介绍了jquery $(document).on('click',selector,...)vs $(selector).on('click',的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以前一直用过:

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

但今天我将这个绑定在docready之后的一个对象上(来自ajax一个调用)。绑定不会坚持。

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.

我已经从jquery休息了一段时间,觉得我错过了一些东西,这些是否存在真正的差异2种方法?它们是什么?

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?

后一种语法是现在对新元素进行绑定的唯一方法(用于服务的livequery插件的目的)?

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

推荐答案

第一个示例将事件侦听器直接绑定到元素。它为每个元素添加一个单独的侦听器,它只会在添加侦听器时响应DOM中元素的事件。

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.

这篇关于jquery $(document).on('click',selector,...)vs $(selector).on('click',的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆