I have to assign mousedown events to an objects collection.
But the .on() method seems to override my objects on each turn.
Here’s a very simplified example of what I have in my code.
The JavaScript :
$(document).ready(function() {
var myArray = {
0: {"id": "box1", "color": "blue"},
1: {"id": "box2", "color": "green"}
};
for (i in myArray) {
box = $('div#'+myArray[i]['id']);
color = myArray[i]['color'];
box.data('color', color);
box.on({
mousedown: function() {
var color = myArray[i]['color'];
$(this).css({'background': $(this).data('color')});
myArray[i]['color'] = (i==0) ? "orange" : "pink";
}
});
}
});
and the HTML:
<div id="container">
<div id="box1"></div>
<div id="box2"></div>
</div>
In addition, you can see it in action here : http://jsfiddle.net/ae3En/6/
Hope someone could help me.
You can use
.eachto iterate over the array and avoid all scope problems through that: