Native JS 相当于 jQuery 委托 [英] Native JS equivalent to jQuery delegation
问题描述
动态创建的 dom 元素的事件委托的本机实现是什么?
What is the native implementation for event delegation on dynamically created dom elements?
我尝试查看 jQuery 源代码,但我无法遵循 .on
方法.
I tried looking at the jQuery source but I can't follow the .on
method.
注意:目前我在创建 dom 元素后附加事件处理程序,这看起来很标准,但我喜欢 jQuery .on
使用这种语法处理动态创建的元素事件的方式 $(文档 ).on( "click", ".selector", handler );
.
Note: Currently I attach the event handlers after the dom elements are created, which seems pretty standard but I like the way jQuery .on
handles dynamically created elements events with this syntax $( document ).on( "click", ".selector", handler );
.
推荐答案
发生的事情基本上是这样的:
What happens is basically this:
// $(document).on("click", <selector>, handler)
document.addEventListener("click", function(e) {
for (var target=e.target; target && target!=this; target=target.parentNode) {
// loop parent nodes from the target to the delegation node
if (target.matches(<selector>)) {
handler.call(target, e);
break;
}
}
}, false);
然而,e.currentTarget
在 handler
被调用时是 document
,而 e.stop[Immediate]Propagation()
会有所不同.jQuery 对此进行了大量抽象(包括调用顺序).
However, e.currentTarget
is document
when the handler
is called, and e.stop[Immediate]Propagation()
will work differently. jQuery abstracts over that (including call order) a lot.
我使用了 .matches()
方法,这还不是标准的,但已经在现代浏览器中以不同的名称提供.您可以使用自定义谓词而不是选择器来测试元素.而addEventListener
显然不兼容旧的IE.
I've used the .matches()
method, which is not yet standard but already available under different names in modern browsers. You might use a custom predicate to test elements instead of a selector. And addEventListener
is obviously not oldIE-compatible.
这篇关于Native JS 相当于 jQuery 委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!