Below is a loop that creates six boxes with different colors. When clicking on a box, the variable “color” changes to the color of the box. There is an obvious problem with the code and that’s closures (all the boxes gets the last class in the array and boxColors[i] isn’t possible to use inside the event (undefined).
How can I solve this in an elegant way? Thanks in advance.
var boxColors = ['red', 'green', 'blue', 'yellow', 'white', 'black'];
for (var i = 0; i < boxColors.length; i++){
$('<div/>', {
'class': boxColors[i]
}).appendTo(toolboxSection1).click(function(){
color = boxColors[i];
});
}
An example of this problem and how to solve it in the general case is described in JavaScript closure inside loops – simple practical example.
However, jQuery allows you to pass additional data to an event handler (see the documentation), which is another way to solve this problem: