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.