javascript - fail to bind onclick event after innerHTML -
var gid = function (id) { homecoming 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 = ''; homecoming false; }; } info.innerhtml += str; } out('1234');
why a#cleanresult fail bind onclick event? alter code, add together settimeout:
settimeout(function () { gid('cleanresult').onclick = function () { info.innerhtml = ''; homecoming false; }; },1); and works.
when alter innerhtml, causes finish rebuild of dom browser. so, in case, final info.innerhtml += str; causes rebuild of dom includes kid objects. therefore, reference cleanresult gets lost.
however, adding onclick binding in settimeout, beingness called after dom has been rebuilt , binding correctly. therefore, should append innerhtml if don't care happened in method. can prepare case follows:
var gid = function (id) { homecoming document.getelementbyid(id); }; function out(str) { var info = gid('info'); if (info.innerhtml.trim() === '') { info.innerhtml += '<a id="cleanresult" href="javascript:;">clean</a><br />'; info.innerhtml += str; gid('cleanresult').onclick = function () { info.innerhtml = ''; homecoming false; }; } else { info.innerhtml += str; } } out('1234'); i have need careful global variable declarations such info. create sure add together var before variable declarations prevent scoping errors.
javascript onclick
No comments:
Post a Comment