var submenus = document.getElementsByClassName("submenu");
for (var i = 0; i < submenus.length; i++) {
submenus[i].onclick = (function(j) {
return function () {
// alert(j);
toggle(submenus[j].nextSibling);
return false;
};
})(i);
}
Because onclick
function will fire after your for
loop, so whenever the user click
on desired element, the i
will be the length
of your elements:
<div class="submenu">Hello</div>
<div class="submenu">Hello</div>
<div class="submenu">Hello</div>
<div class="submenu">Hello</div>
<div class="submenu">Hello</div>
<div class="submenu">Hello</div>
And with your code:
var submenus = document.getElementsByClassName("submenu");
for (var i = 0; i < submenus.length; i++) {
submenus[i].onclick = function() {
alert(i);
}
}
You'll get 6
for i
on every element (check the jsFiddle).
You must keep i
inside the onclick
function, closure will help you:
for (var i = 0; i < submenus.length; i++) {
submenus[i].onclick = (function(j) {
return function () {
alert(j);
};
})(i);
}
As you see, I've created a function and execute it immediately (with a parameter I've called it j
, and the value of it, for each element, is the i
).
The return of it, is another function.
Check this jsFiddle.