Reputation: 840
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')?
Upvotes: 0
Views: 41
Reputation: 840
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
}
Upvotes: 0
Reputation: 42736
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);
}
Upvotes: 2