$(document).on('click', '#id', function() {}) vs $('#id').on('click', function(){}) [英] $(document).on('click', '#id', function() {}) vs $('#id').on('click', function(){})

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

问题描述

我试图找出两者之间的区别

I was trying to find out what is the difference between

$(document).on('click', '#id', function(){});

$('#id').on('click', function(){});

我无法找到有关两者之间是否有任何区别的任何信息,如果有,可能有什么区别.

I've not been able to find any information on if there is any difference between the two, and if so what that difference may be.

有人可以解释一下是否有任何区别吗?

Can someone please explain if there is any difference at all?

推荐答案

第一个示例演示了事件委托.事件处理程序绑定到 DOM 树上的一个元素(在本例中为 document),并且将在事件到达该元素时执行,该元素源自与选择器匹配的元素.

The first example demonstrates event delegation. The event handler is bound to an element higher up the DOM tree (in this case, the document) and will be executed when an event reaches that element having originated on an element matching the selector.

这是可能的,因为大多数 DOM 事件从原点冒泡树.如果您单击 #id 元素,则会生成一个单击事件,该事件将通过所有祖先元素向上冒泡(旁注:在此之前实际上有一个阶段,称为捕获"阶段',当事件沿着树向下到达目标时).您可以在这些祖先中的任何一个上捕获事件.

This is possible because most DOM events bubble up the tree from the point of origin. If you click on the #id element, a click event is generated that will bubble up through all of the ancestor elements (side note: there is actually a phase before this, called the 'capture phase', when the event comes down the tree to the target). You can capture the event on any of those ancestors.

第二个示例将事件处理程序直接绑定到元素.该事件仍然会冒泡(除非您在处理程序中阻止它),但由于处理程序绑定到目标,您将看不到此过程的效果.

The second example binds the event handler directly to the element. The event will still bubble (unless you prevent that in the handler) but since the handler is bound to the target, you won't see the effects of this process.

通过委托事件处理程序,您可以确保为绑定时在 DOM 中不存在的元素执行它.如果您的 #id 元素是在您的第二个示例之后创建的,您的处理程序将永远不会执行.通过绑定到一个在执行时你知道肯定在 DOM 中的元素,你可以确保你的处理程序实际上附加到某些东西上,并且可以在以后适当地执行.

By delegating an event handler, you can ensure it is executed for elements that did not exist in the DOM at the time of binding. If your #id element was created after your second example, your handler would never execute. By binding to an element that you know is definitely in the DOM at the time of execution, you ensure that your handler will actually be attached to something and can be executed as appropriate later on.

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

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