Search code examples
javascriptdom-events

JavaScript set DOM object event dynamically on dynamically created DOM objects


The following script:

var containerDIV = document.getElementById("sampleContainer");

for(var i = 0; i < 5; i++)
{
    var dynamicDIV = document.createElement("div");
    containerDIV.appendChild(dynamicDIV);   
    dynamicDIV.onclick = function() { alert(i); };
    dynamicDIV.innerHTML = "Row: " + i;
}

when clicking on the dynamically rows the output in the alert box will always be "5" instead of 0, 1, ..

Do anyone knows a proper way to assign the onclick event?


Solution

  • You should use the closure power:

    for (var i = 0; i < 5; i++) {
        (function(i) {
            dynamicDIV.onclick = function() {
                alert(i);
            };
        })(i);
    }
    

    DEMO: http://jsfiddle.net/zvPfZ/