0

I am trying to assign an onclick function to different types of items. So, within a for loop I have if(invType[i] != "empty") within that if statement I have

if(invType[i] == "usable"){
    document.getElementById(i).onclick = function(i){ return function(){useItem(invName[i],i)}; }(i);
}
if(invType[i] == "equipment"){
    document.getElementById(i).onclick = function(i){ return function(){equipItem(invName[i],i)}; }(i);
}

only the last non-"empty" item is getting assigned the onclick function, and I have no clue why. I need it to assign the onclick to every "usable" or "equipment" not just the last one.

isaac tschampl
  • 388
  • 2
  • 12
  • 2
    Because by the time your `for` loop has completed, `i` is setting at one past the last value of the `for` loop and that's the value that `i` has some time in the future when you `onclick` handler is actually called. This is a duplicate question of many previous answers. I will try to find one of those dups. – jfriend00 Sep 23 '15 at 03:39
  • Also see this answer: [Asynchronous Process inside a javascript for loop](http://stackoverflow.com/questions/11488014/asynchronous-process-inside-a-javascript-for-loop/11488129#11488129). – jfriend00 Sep 23 '15 at 03:41

0 Answers0