I am trying to create on-the-fly an a element and to set it an on-click function with alert.
I am familiar with the closure in JavaScript so I am aware of that I cannot call it directly like doc.onclick=function() {alert(i);} since it will have the value of the last i. so I tried to call the function immediately but it's also popup the alert immediately. how can I solve this issue?
for (var i=0; i < 5; ++i) {
var doc = document.createElement("a");
doc.innerHTML = i;
doc.onclick = function(i) {alert(i);}(i);
document.body.appendChild(doc);
}
doc.onclick = function () { alert(this.innerHTML); };ordoc.addEventListener('click', function () { alert(this.innerHTML); });