简体   繁体   中英

Event listener with parameters and innerHTML only works once

I have a script that adds some text to page, like so:

document.body.innerHTML += '<input type="image" id="alertMeID" style="position:fixed;top:0;left:0" //src="http://i55.tinypic.com/2nly5wz.gif" ///>';
document.body.innerHTML += '<input type="image" id="alertMeID2" style="position:fixed;top:100;left:100" //src="http://i55.tinypic.com/2nly5wz.gif" />';
document.getElementById('alertMeID').addEventListener('click', function(){do_this("some text")}, false);
document.getElementById('alertMeID2').addEventListener('click', function(){do_this("another text")}, false);

function do_this(sendingParameter){document.body.innerHTML += sendingParameter;}

The first time I click on one of the images it works properly. But, if I click a second time, it doesn't work at all.

How to solve this problem?

When you use innerHTML the element's content gets reparsed. The elements are removed and recreated, which in turn removes the event handler. Much better would be to use DOM manipulation.

function do_this(sendingParameter){
    document.body.appendChild(document.createTextNode(sendingParameter));
}

Demo: http://jsfiddle.net/mdtSY/

You might also want to take a look at: insertAdjacentHTML

It states at mdn :

insertAdjacentHTML() parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position. It does not reparse the element it is being used on and thus it does not corrupt the existing elements inside that element. This avoids the extra step of serialization, making it much faster than direct innerHTML manipulation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM