0

I'm attaching listener to all the children of a div, how to make them to alert with their number relative to their parent. Because the function executes the actual variable i, not when attached.

var nodes = div.children; //10 nodes
for (var i = 0; i < nodes.length; i++) {
    nodes[i].onclick = function () {alert(i)}
}

So the only solution is to use eval('i')?

2 Answers 2

2

Use a closure and pass the index

var nodes = div.children; //10 nodes
for (var i = 0; i < nodes.length; i++) {
    (function(index){
       nodes[index].onclick = function () {alert(index)}
    })(i);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Another two possible answer could be:

nodes[i].setAttribute('onclick','alert('+i+')');

or:

nodes[i].setAttribute('index', i);
nodes[i].onclick = function(){
    alert(this.getAttribute('index')); 
    //remember attribute index is string, so do parseInt() when required
}

Comments

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.