Create a new scope (closure) to keep the value of i
, as by the time the asynchronous onload
handler fires, the loop has finished, and the value of i
will be the last one set, passing it to an IIFE solves this
$('input').change(function () {
for (var i=0, len = this.files.length; i < len; i++) {
(function (j, self) {
var reader = new FileReader()
reader.onload = function (e) {
$('ul').append('<li><img src="' + e.target.result + '">' + self.files[j].name + '</li>')
}
reader.readAsDataURL(self.files[j])
})(i, this);
}
});