javascript 在innerHTML 生成的div 上单击事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31876652/
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
click event on innerHTML generated div
提问by
I have a 'div' element generated in javascript with 'innerHTML' property.
我有一个在 javascript 中生成的具有 'innerHTML' 属性的 'div' 元素。
(...).innerHTML = 'sometext'+'<div id=\"a\">word</div>'+obj.something+'othertext';
Anyway onclick event is not working.
无论如何 onclick 事件不起作用。
document.getElementById('a').onclick = function() {
//do something
}
What is the problem? How do I resolve it (pure javascript, no libraries)?
问题是什么?我如何解决它(纯 javascript,没有库)?
采纳答案by Nillus
You could delegate the event listening to the parent to which you are innerHTML-ing the div , in yout code indicated by (...). This would handle the events fired in the (...) and you can perform actions conditioned to event.target.id === 'a'
您可以在由 (...) 指示的代码中将侦听事件委托给您正在对 div 进行 HTML 处理的父级。这将处理 (...) 中触发的事件,您可以执行以 event.target.id === 'a' 为条件的操作
(...).onclick = function(event) {
if (event.target.id === 'a') {
//Do your stuff
}
}
This way you not need to worry about if, when you attach the listener, you have already created the div dinamically or not. Also, to register the event handler, I suggest proper event handle registering (https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener)
这样您就不必担心,当您附加侦听器时,您是否已经以动态方式创建了 div。另外,要注册事件处理程序,我建议正确的事件处理程序注册(https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener)
回答by Harshit Gupta
You need to bind that id with the function after you added the the innerhtml to the outer html
将innerhtml添加到外部html后,您需要将该id与函数绑定
function bindingFunction(){
document.getElementById('a').onclick = function() {
// Your code
}
}
Just after adding the innerHTML
添加innerHTML后
(...).innerHTML = 'sometext'+'<div id=\"a\">word</div>'+obj.something+'othertext';
bindingFunction();
This will work.
这将起作用。
回答by Sumit
Working Example:
工作示例:
Javascript Code
Javascript代码
document.getElementById('resultDiv').innerHTML = '<div id=\"a\">Test onclick</div>';
document.getElementById('a').onclick = function() {
alert("Click Event Fired !")
}
Demo for you: https://jsfiddle.net/be3a90gw/4/
回答by Solutionswithus
Please call this function :
请调用这个函数:
document.getElementById('a').onclick = function() {
//do something
}
Just after the
就在
(...).innerHTML = 'sometext'+'<div id=\"a\">word</div>'+obj.something+'othertext';