我有一个在 javascript 中生成的带有“innerHTML”属性的“div”元素。
(...).innerHTML = 'sometext'+'<div id=\"a\">word</div>'+obj.something+'othertext';
无论如何,onclick 事件不起作用。
document.getElementById('a').onclick = function() {
//do something
}
问题是什么?我该如何解决(纯 JavaScript,无库)?
最佳答案
在将内部 html 添加到外部 html 之后,您需要将该 id 与函数绑定(bind)
function bindingFunction(){
document.getElementById('a').onclick = function() {
// Your code
}
}
在添加 innerHTML 之后
(...).innerHTML = 'sometext'+'<div id=\"a\">word</div>'+obj.something+'othertext';
bindingFunction();
这会起作用。
关于javascript - innerHTML 生成的 div 上的点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31876652/