添加innerHTML后addEventListener消失
好的,我使用 javascript/greasemonkey 将以下 html 添加到网站中。 (只是示例)
<ul>
<li><a id='abc'>HEllo</a></li>
<li><a id='xyz'>Hello</a></li>
</ul>
,我还为元素添加了一个单击事件侦听器。 到目前为止,一切正常,当我单击该元素时,单击事件将被触发。
但是......我在脚本中有另一个函数,它在一定条件下修改该html, 即它附加它,所以它看起来像:
<ul>
<li><a id='abc'>Hello</a></li>
<li><a id='xyz'>Hello</a></li>
<li><a id='123'>Hello</a></li>
</ul>
但是当这完成时,它破坏了我为前两个元素添加的侦听器...... 当我点击它们时什么也没有发生。
如果我注释掉对执行附加操作的函数的调用,一切都会再次开始工作!
请帮忙...
Okay, so i have the following html added to a site using javascript/greasemonkey.
(just sample)
<ul>
<li><a id='abc'>HEllo</a></li>
<li><a id='xyz'>Hello</a></li>
</ul>
and i've also added a click event listener for the elements.
All works fine up to this point, the click event gets fired when i click the element.
But... i have another function in the script, which upon a certain condition, modifies that html,
ie it appends it, so it looks like:
<ul>
<li><a id='abc'>Hello</a></li>
<li><a id='xyz'>Hello</a></li>
<li><a id='123'>Hello</a></li>
</ul>
but when this is done, it breaks the listeners i added for the first two elements...
nothing happens when i click them.
if i comment out the call to the function which does the appending, it all starts working again!
help please...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
每次设置
innerHTML
属性时,您都会覆盖之前设置的任何 HTML。这包括串联赋值,因为与编写相同。
这意味着所有未通过 HTML 属性附加的处理程序都将被“分离”,因为它们附加的元素不再存在,并且一组新的元素已取代它们。要保留所有以前的事件处理程序,您必须附加元素而不覆盖任何以前的 HTML。最好的方法是使用 DOM 创建函数,例如
createElement
和appendChild
:Any time you set the
innerHTML
property you are overwriting any previous HTML that was set there. This includes concatenation assignment, becauseis the same as writing
This means all handlers not attached via HTML attributes will be "detached", since the elements they were attached to no longer exist, and a new set of elements has taken their place. To keep all your previous event handlers, you have to append elements without overwriting any previous HTML. The best way to do this is to use DOM creation functions such as
createElement
andappendChild
:作为一种变体,您可以添加这样的 html,它无需 addEventListener 即可工作:
As an variant, you can add such html, which will work without addEventListener:
你还可以使用 jQuery 的“live”功能
U can also use jQuery's 'live' function