var submenus = document.getElementsByClassName("submenu"); for (var i = 0; i < submenus.length; i++) { submenus[i].onclick = (function(j) { return function () {
Because the onclick function fires after your for loop, so whenever the user clicks on the desired element i will be the length 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 will get 6 for i for each element (check jsFiddle ).
You must save i inside the onclick function, closing will help you:
for (var i = 0; i < submenus.length; i++) { submenus[i].onclick = (function(j) { return function () { alert(j); }; })(i); }
As you can see, I created a function and immediately executed it (with the parameter that I called j ), and the value for each element is i ). Return is another function. Check out jsFiddle .
user1823761
source share