innerHTML生成的div上的click事件 [英] click event on innerHTML generated div
问题描述
我在javascript中使用'innerHTML'属性生成了一个'div'元素.
I have a 'div' element generated in javascript with 'innerHTML' property.
(...).innerHTML = 'sometext'+'<div id=\"a\">word</div>'+obj.something+'othertext';
无论如何,onclick事件均不起作用.
Anyway onclick event is not working.
document.getElementById('a').onclick = function() {
//do something
}
出什么问题了?我该如何解决(纯JavaScript,无库)?
What is the problem? How do I resolve it (pure javascript, no libraries)?
推荐答案
您可以使用(...)指示的代码,将事件委托给正在对其进行内部HTML处理的父级侦听div.这将处理(...)中触发的事件,并且您可以执行以event.target.id ==='a'
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'
(...).onclick = function(event) {
if (event.target.id === 'a') {
//Do your stuff
}
}
这样,您无需担心在附加侦听器时是否已经动态创建了div.另外,要注册事件处理程序,我建议适当的事件句柄注册(https://developer.mozilla.org/zh-CN/docs/Web/API/EventTarget/addEventListener )
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)
这篇关于innerHTML生成的div上的click事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!