更新时间:2023-09-29 19:52:28
您可以使用(...)指示的代码,将事件委托给正在对其进行内部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)