修改 DOM 后,绑定的事件监听器为什么不再触发?

January 27, 2024

我用下面的代码向 body 追加元素时遇到了这个问题。

    let p = document.createElement("p");
    p.innerHTML = `some text`
    document.body.appendChild(p);

我原先用下面的 JavaScript 和 HTML 给按钮绑定点击事件。

    <body>
        <h1>Hello, World!</h1>
        <button id="btn">click</button>
    </body>

    <script>
        const btn = document.getElementById('btn');
        btn.addEventListener('click', () => {})
    </script>

在我当时的页面里,追加元素后,点击按钮就不再触发原先的处理函数了。

我当时的处理办法是直接在按钮上写 onclick:

    <button id="btn" onclick="btnHandler()">click</button>

© 2024 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2024-01-27). 修改 DOM 后,绑定的事件监听器为什么不再触发?. https://caiborui.com/blog/2024-01-27-en-event-listener-rebinding-zhtrans

@misc{borui2024-ad60ebcc,
  author = {borui},
  title = {{修改 DOM 后,绑定的事件监听器为什么不再触发?}},
  year = {2024},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2024-01-27-en-event-listener-rebinding-zhtrans}
}