如何将EventListener添加到将来的dom元素? [英] How to addEventListener to future dom elements?
问题描述
partial.html文件如下所示:<button id="test">Hi I am from a partial!</button>
File partial.html looks like this: <button id="test">Hi I am from a partial!</button>
Partial.html
使用XMLHttpRequest
动态包含在页面上:
Partial.html
is dynamically included on the page, using XMLHttpRequest
:
var oReq = new XMLHttpRequest();
oReq.open('get', 'partial.html', true);
oReq.send();
oReq.onload = function(){
document.querySelector('#pageArea').innerHTML = this.response;
}
}
如何添加一个事件侦听器,该事件侦听器将应用于将来已存在的#test
,并且在将其内容加载并插入到#pageArea
中后不做任何事情?
How can I add an event listener that will apply to future exisiting #test
without doing it after it's content has been loaded and inserted into #pageArea
?
(请没有jQuery解决方案!)
推荐答案
Events like click bubble, so you attach the event handler to the closest non-dynamic parent, and inside the event handler you check if it was the button being clicked by seeing if it was the event's target :
var parent = document.getElementById('pageArea');
if (parent.addEventListener) {
parent.addEventListener('click', handler, false);
}else if (parent.attachEvent) {
parent.attachEvent('onclick', handler);
}
function handler(e) {
if (e.target.id == 'test') {
// the button was clicked
}
}
这篇关于如何将EventListener添加到将来的dom元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!