You're running into trouble with doing async calls inside of js. This is a common problem and it's describe here:
http://dojo-toolkit.33424.n3.nabble.com/Advice-on-closures-and-retaining-variable-values-inside-async-handlers-e-g-xhrGet-td3227726.html
Basically the value of i
is equal to 9
by the time your console.log is actually ran.
There are many ways to solve this problem in general, but your specific solution should probably be to restructure things immensely. Consider this alternative (requires jQuery), but we could do the same without it very easily.
$.each(results, function(data) {
var $el = $("<div></div>").html(data.name).click(function() { console.log(data) });
})
But it would be even better to use jQuery.data() to store things and then use .on()
or .delegate()
to listen for the click events like this
$.each(results, function(data) {
var $el = $("<div></div>").addClass("yourThing").html(data.name).data("data", data);
})
// replace window with a closer parent if one exists
$(window).on("click", ".yourThing", function() {
console.log($(this).data("data")); // retrieve data from jquerys .data() store
});