You're running into a classical example of how references work in JavaScript. When the success
callback is called, the value of i
is always 2
because it already changed to the next iteration. What you need to do is wrap each callback in another function so each of them points to a different value of i
.
for (var i = 1; i < 3; i++) {
Y.io(url, {
on: {
// on each iteration the success function is a different function
success: (function (index) {
return function (msg, result) {
Y.one('#display_div' + index).setHTML(msg);
};
}(i)); // we pass it the current value of i
}
});
}