我在试着找出两者之间的区别

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

and

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

我还找不到任何关于这两者之间是否有区别的信息,如果有的话,区别可能是什么.

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

推荐答案

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事件bubble从原点沿树向上.如果您点击第#id个元素,则会生成一个点击事件,该事件将向上泡沫遍历所有祖先元素(side note: there is actually a phase before this, called the 'capture phase', when the event comes down the tree to the target).您可以在这些祖先中的任何一个上捕获事件.

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.

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.

Jquery相关问答推荐

使用jQuery筛选器搜索输入仅适用于单词的一部分

从文本区域获取值

jQuery javascript 正则表达式 将
替换为 \n

jQuery - 获取 ajax POST 的表单值

如何判断输入日期是否等于今天的日期?

jQuery $.browser 是否已弃用?

非 AJAX jQuery POST 请求

JQuery 仅在 Rails 4 应用程序中的页面刷新时加载

如何使用Angular 检测浏览器后退按钮单击事件?

jQuery UI 对话框 - 关闭后不打开

如何在 Backbone.js - Backbone.sync 或 jQuery.ajax 中保存整个集合?

使用 jQuery 验证插件自定义日期格式

点击时保持 Bootstrap 下拉菜单打开

datatable jquery - 表头宽度与正文宽度不对齐

为 jQuery AJAX 调用实现加载指示器

捕获在页面任意位置按下的 Enter 键

Url.Action 在我的 url 中放了一个 &,我该如何解决这个问题?

jquery更改div类的样式属性

在jQuery中获取CSS规则的百分比值

用于发布和获取的 Ajax 教程