I am relatively new to javascript and I'm struggling to find a solution for the following issue. In this example, I am using Mootools, but my question is not specific to Mootools:
for (var i = 0; i < 5; i++) {
myElement[i].addEvent('click', function () { otherFunction(i); });
}
When a user clicks on myElement, otherFunction is triggered (great), but it receives the value of 5 (not so great). I understand that this happens because it accesses the value of i after the loop has finished executing, at the time of the click event. Despite racking my brain, I can't seem to come up with an alternative solution besides the tedious:
switch(i) {
case 1: myElement[i].addEvent('click', function () { otherFunction(1); }); break;
case 2: myElement[i].addEvent('click', function () { otherFunction(2); }); break;
// ...
}
There must be a more elegant way... I have a feeling that I'm overlooking something obvious.
UPDATE: Added [i] index to myElement (oops)
Thanks, Cameron