I create a nodelist that selects 2 divs. Then I create a function to show the index of the div that the user clicks. But the output is always be 2. I don't figure out where the mistake is.
This is just a simple problem, but it will solve my other complex problems with many events inside events. Thanks.
HTML:
<div style="background:red; height:50px"></div>
<div style="background:black; height:50px"></div>
Javascript:
var div = document.getElementsByTagName('div');
for (i = 0; i < div.length; i++) {
div[i].onclick = function() {
alert(i);
}
}
Try this:
In your case, value of
i
is nothing but a valuei
has at the end of the loop which islength-1
of node list.
var div = document.getElementsByTagName('div');
for (i = 0; i < div.length; i++) {
div[i].onclick = (function(i) {
return function() {
alert(i);
}
})(i)
}
<div style="background:red; height:50px"></div>
<div style="background:black; height:50px"></div>