我在试着找出两者之间的区别
$(document).on('click', '#id', function(){});
and
$('#id').on('click', function(){});
我还找不到任何关于这两者之间是否有区别的信息,如果有的话,区别可能是什么.
Can someone please explain if there is any difference at all?
我在试着找出两者之间的区别
$(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.