javascript appendChild 之后的 addEventListener
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21292657/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
addEventListener after appendChild
提问by Leo
I create an element, eltTooltip
, with document.createElement
etc and add it to the DOM like this (idTooltip
contains the id
of eltTooltip
):
我创建了一个元素, eltTooltip
, 和document.createElement
etc 并将它的添加到 DOM 像这样(idTooltip
包含id
of eltTooltip
):
document.body.appendChild(eltTooltip);
var addedElt = document.getElementById(idTooltip);
addedElt.addEventListener("click", function(){...});
Is the click
event guaranteed to be added here, or is perhaps the DOM not ready for that?
click
事件是否保证会被添加到这里,或者 DOM 可能还没有准备好?
Could I do this in a better way? (The page is loaded long ago so window.onload
can not be used. And I can't use jQuery here.)
我能以更好的方式做到这一点吗?(页面很久以前加载所以window.onload
无法使用。我不能在这里使用jQuery。)
回答by Daniel Imms
Your way works perfectly fine but it's probably better to attach the event listener before you add it to the DOM using eltTooltip
. This saves you from fetching the element from the DOM.
你的方式工作得很好,但在使用eltTooltip
. 这使您无需从 DOM 中获取元素。
var idTooltip = 'test';
var eltTooltip = document.createElement('div');
eltTooltip.innerHTML = "test"
eltTooltip.setAttribute('id', idTooltip);
eltTooltip.addEventListener("click", function () {
alert('click');
});
document.body.appendChild(eltTooltip);
回答by Suman Bogati
You could do something like this
你可以做这样的事情
window.onload = function (){
var toolTip = document.createElement('div');
toolTip.innerHTML = "someData";
toolTip.addEventListener('click', myfunction);
document.body.appendChild(toolTip);
function myfunction(){
alert("hello guys ");
}
}