如何在新创建的元素上应用 add_event_listener() ?
当 DOM 已加载时,我使用此脚本应用 add_event_listener() 。
document.addEventListener("DOMContentLoaded",regFunct,false);
然后我列出了 regFunct 函数内的所有函数。 从服务器加载的 regFunct
内的所有函数都在工作,除了使用 appendChild()
新创建的元素。
function regFunct(){
//doSomething1
//doSomething2 (create new HTML element)
//doSomething3 (apply add_event_listener() after
// the new element created by doSomething2)
}
doSomething3 不起作用。
I am using this script to apply add_event_listener() when the DOM is already loaded.
document.addEventListener("DOMContentLoaded",regFunct,false);
then I list all the function inside regFunct
function.
all the function inside the regFunct
which is loaded from the server are working except the newly created element using appendChild()
.
function regFunct(){
//doSomething1
//doSomething2 (create new HTML element)
//doSomething3 (apply add_event_listener() after
// the new element created by doSomething2)
}
doSomething3 is not working.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于仅在已触发
DOMContentLoaded
事件之后创建的元素,您可以创建一个委托侦听器。这是一种可能的方法。假设您想要监听动态添加的具有
id
myNewButton
的button
上的click
事件:请注意,这仅适用于冒泡的事件。默认情况下不冒泡的事件示例:
scroll
、blur
、focus
。For elements that are created only after the
DOMContentLoaded
event already fired, you can create a delegate listener.Here's one possible approach. Let's assume you want to listen to the
click
event on a dynamically addedbutton
that has theid
myNewButton
:Please note that this only works for events that bubble. Examples of events that don't bubble by default:
scroll
,blur
,focus
.