0

I'm in a bind about how to propagate these onclick functions with useful arguments. I'm relatively new to js and I'm still getting used to the idea of functions as vars.

Here is the code:

for (var i = 0; i < this.level; i++) {
    var splotch = document.createElement('div');
    // ...
    // Omitted some styling and formatting
    // ...
    splotch.onclick = function() { switchColor(i); }; // The issue lies here
    pallet.appendChild(splotch);
}

The loop is designed to create a small pallet of colors which the user may choose from. The onclick events should be iteration-specific. That is, in HTML, the attributes would look something like:

onclick="switchColor(0)"
onclick="switchColor(1)"
// etc...

The argument however, is invariably the value of i that is one more than this.level, indicating to me that the value of i does not persist in each instance of the function, but rather the reference to i.

How might I mend this? And if my approach does not reflect best practice, I'd appreciate your adjustments.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
K1nesthesia
  • 147
  • 1
  • 3
  • 11
  • possible duplicate: http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – d0c Jul 12 '14 at 04:32
  • the `onclick` function, when clicked, will run in it's own scope and not within the scope of the for loop (which could have ended a long time ago as far as the page as concerned). `i` within the function ends up acting like an implicit global, which, since you (likely) ran the for loop in global scope means that `i` is persisting from the last iteration of the loop. As in the possible duplicate, a solution can be something like: `function createSwitchColor(x) { return function () { switchColor(x) }; } //... code splotch.onclick = createSwitchColor(i);` – serakfalcon Jul 12 '14 at 04:47

0 Answers0