0

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?

1 Answer 1

1

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/

Sign up to request clarification or add additional context in comments.

2 Comments

thanks it definitely works!! I still can't understand why but i hope to get it after reading the mozilla dev article :) Have a nice day!
@steax Closures is one of the most important features of JavaScript. I suggest you to read about it. Good day ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.