Sunday, November 11, 2012

javascript – How can I use jQuery .on() method in a loop, without overriding the objects on which I loop

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, thanks.






Rating: 1 out of 5 based on 6 ratings



The post javascript – How can I use jQuery .on() method in a loop, without overriding the objects on which I loop appeared first on Javascript ASK.






via Javascript ASK http://javascriptask.phpfogapp.com/javascript-how-can-i-use-jquery-on-method-in-a-loop-without-overriding-the-objects-on-which-i-loop.html

No comments:

Post a Comment