问题描述
考虑一个基本的 addEventListener
as
Consider a basic addEventListener
as
window.onload=function(){
document.getElementById("alert")
.addEventListener('click', function(){
alert("OK");
}, false);
}
其中< div id =alert> ; ALERT< / div>
在原始文档中不存在,我们通过AJAX从外部源调用它。我们如何强制 addEventListener
来处理文档中新添加的元素(在的初始扫描之后
window.onload
)
where <div id="alert">ALERT</div>
does not exist in the original document and we call it from an external source by AJAX. How we can force addEventListener
to work for newly added elements to the documents (after initial scan of DOM elements by window.onload
)?
在jQuery中,我们通过 live()
或委托来执行此操作( )
;但我们如何在纯Javascript中使用 addEventListener
来做到这一点?事实上,我正在寻找相当于 delegate()
,因为 live()
附加事件到根文件;我希望在父级
的水平上进行新的事件。
In jQuery, we do this by live()
or delegate()
; but how we can do this with addEventListener
in pure Javascript? As a matter of fact, I am looking for the equivalent to delegate()
, as live()
attaches the event to the root document; I wish to make a fresh event listening at the level of parent
.
推荐答案
过度简化,离jQuery的事件系统很远,但基本的想法就在那里。
Overly simplified and is very far away from jQuery's event system but the basic idea is there.
var div = document.createElement("div"),
prefix = ["moz","webkit","ms","o"].filter(function(prefix){
return prefix+"MatchesSelector" in div;
})[0] + "MatchesSelector";
Element.prototype.addDelegateListener = function( type, selector, fn ) {
this.addEventListener( type, function(e){
var target = e.target;
while( target && target !== this && !target[prefix](selector) ) {
target = target.parentNode;
}
if( target && target !== this ) {
return fn.call( target, e );
}
}, false );
};
您对此缺失:
- 性能优化,每个委托侦听器都会运行一个完整的循环,所以如果你在一个元素上添加很多,你将运行所有这些循环
- 可写事件对象。所以你无法修复
e.currentTarget
这是非常重要的,因为这个
通常被用作对某个实例的引用 - 没有数据存储实现,所以除非你每次都手动创建函数,否则没有好的方法来删除处理程序
- 只支持冒泡事件,所以没有
更改
或提交
等您认为是理所当然的jQuery - 我现在忘记的其他许多人
- Performance optimizations, every delegate listener will run a full loop so if you add many on a single element, you will run all these loops
- Writable event object. So you cannot fix
e.currentTarget
which is very important sincethis
is usually used as a reference to some instance - There is no data store implementation so there is no good way to remove the handlers unless you make the functions manually everytime
- Only bubbling events are supported, so no
"change"
or"submit"
etc which you took for granted with jQuery - Many others which I'm simply forgetting about for now
这篇关于addEventListener用于新元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!