var gid = function (id) {
return document.getElementById(id);
},
info = gid('info');
function out(str) {
if ((info.innerHTML + '').trim() === '') {
info.innerHTML += '<a id="cleanResult" href="javascript:;">clean</a><br />';
gid('cleanResult').onclick = function () {
info.innerHTML = '';
return false;
};
}
info.innerHTML += str;
}
out('1234');
Why a#cleanResult fail to bind onclick event?
I change the code, add setTimeout:
setTimeout(function () {
gid('cleanResult').onclick = function () {
info.innerHTML = '';
return false;
};
},1);
and it works.
When you change the
innerHTML, this causes a complete rebuild of the DOM by the browser. So, in this case, your finalinfo.innerHTML += str;causes a rebuild of the DOM which includes child objects. Therefore, your reference tocleanResultgets lost.However, by adding your
onclickbinding in asetTimeout, you are being called after the DOM has been rebuilt and thus binding correctly. Therefore, you should only append to innerHTML if you don’t care about what just happened previously in the method. You can fix your case as follows:I also have to say that you need to be very careful about global variable declarations such as
info. Always make sure to addvarbefore your variable declarations to prevent scoping errors.