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

s25g5d4
  • 23
  • 3

1 Answers1

1

When you change the innerHTML, this causes a complete rebuild of the DOM by the browser. So, in this case, your final info.innerHTML += str; causes a rebuild of the DOM which includes child objects. Therefore, your reference to cleanResult gets lost.

However, by adding your onclick binding in a setTimeout, 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:

var gid = function (id) {
    return 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 = '';
            return false;
        };
    } else {
        info.innerHTML += str;
    }
}
out('1234');

I also have to say that you need to be very careful about global variable declarations such as info. Always make sure to add var before your variable declarations to prevent scoping errors.

BeRecursive
  • 6,286
  • 1
  • 24
  • 41