Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

javascript - addEventListener gone after appending innerHTML

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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>';

is the same as writing

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

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...