addEventListener在追加innerHTML后消失了 [英] addEventListener gone after appending innerHTML

查看:429
本文介绍了addEventListener在追加innerHTML后消失了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我使用javascript / greasemonkey将以下html添加到网站。
(只是样品)

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>

我还为元素添加了一个click事件监听器。
到目前为止一切正常,单击元素时会触发click事件。

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.

但是...我在脚本中有另一个函数,在某种情况下,修改html,
即它附加它,所以它看起来像:

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!

请帮助...

推荐答案

每次设置 innerHTML 属性,您将覆盖之前设置的任何HTML。这包括连接分配,因为

Any time you set the innerHTML property you are overwriting any previous HTML that was set there. This includes concatenation assignment, because

element.innerHTML += '<b>Hello</b>';

与写作相同

element.innerHTML = element.innerHTML + '<b>Hello</b>';

这意味着所有未通过HTML属性附加的处理程序将被分离,因为它们附加的元素不再存在,一系列新元素取代了它们。要保留以前的所有事件处理程序,您必须附加元素而不覆盖任何以前的HTML。执行此操作的最佳方法是使用DOM创建函数,例如 createElement appendChild

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 and appendChild:

var menu = pmgroot.getElementsByTagName("ul")[0];
var aEl  = document.createElement("a");
aEl.innerHTML = "Hello";
aEl.id "123";
menu.appendChild(aEl);

这篇关于addEventListener在追加innerHTML后消失了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆