I need to assign mousedown events to a collection of objects.
But the .on () method seems to override my objects at every step.
Here is a very simplified example of what I have in my code.
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 HTML:
<div id="container"> <div id="box1"></div> <div id="box2"></div> </div>
Alternatively, you can see this in action here: http://jsfiddle.net/ae3En/6/
Hope someone can help me, thanks.
source share