0

I have this code in a for loop and it's supposed to make all the items do the useItem function with their name as the parameter

if(invType[i] == "usable"){
    console.log(invName[i]);
    document.getElementById(i).onclick = function(){useItem(invName[i])};
}

and then this is the useItem function

function useItem(object){
    switch(object){
        case "sword":
            console.log("sword");
            break;
    }
    console.log("finished");
}

What is happening is that in the for loop console.log(invName[i]); is printing "sword" as it should, and it assigns the element the onclick function ok, but it isn't outputting what it should. It always thinks its undefined, so case "sword": never runs, but it does print "finished" fine. I just cant see what could be going wrong here.

Renato Gama
  • 16,431
  • 12
  • 58
  • 92
isaac tschampl
  • 388
  • 2
  • 12
  • 5
    `object` is a reserved word, so you should change that to something else (`obj`, for instance). That probably isn't causing your problem here though. – James Donnelly Sep 22 '15 at 15:21
  • 1
    When you write `document.getElementById(i).onclick = function(){useItem(invName[i])};` the variable `i` won't stick to the value you put in the function. You need to say `document.getElementById(i).onclick = function(i) { return function(){useItem(invName[i])}; }(i);` – Dave Chen Sep 22 '15 at 15:24
  • That solved it, why do I need the (i) at the very end though? – isaac tschampl Sep 22 '15 at 15:30

0 Answers0