本机JS相当于jquery授权 [英] Native JS equivalent to jquery delegation
问题描述
我尝试查看jquery源代码,但我无法遵循.on方法。
p>注意:目前我在创建dom元素后附加了事件处理程序,这似乎很标准,但我喜欢jquery .on处理动态创建的元素事件与这种语法的方式$(文件).on(click,.selector,handler);
p>
// $(document).on(click,< selector>处理程序)
document.addEventListener click,function(e){
for(var target = e.target; target&& target!= this; target = target.parentNode){
//循环父节点目标到代理节点
if(target.matches(< selector>)){
handler.call(target,e);
break;
}
}
},false);
但是, e.currentTarget
是<$调用处理程序
时,c $ c> document , e.stop [Immediate] Propagation()
将会有所不同。 jQuery抽象(包括调用顺序)很多。
我使用了 .matches()
方法,它还不是标准的,但现代浏览器中的名称不同。您可以使用自定义谓词来测试元素而不是选择器。而 addEventListener
显然不是oldIE兼容的。
What is the native implementation for event delegation on dynamically created dom elements?
I tried looking at the jquery source but I cant follow the .on method.
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);
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.
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.
这篇关于本机JS相当于jquery授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!