0

I'm trying to do thumbnails for the images uploaded. I want to create diferents classes for the thumbs, for this, I'm trying to use de i of the loop. But this assume just the final value. Why? Thanks

for (var i = 0; i < inp.files.length; i++) {

//create the thumbnails
 var reader = new FileReader();
reader.onload = function (e) {
    $('.thumbs').append('<div class="thumb_item" id="c'+ i +'"></div>');
    $('<img />').attr({'src': e.target.result}).addClass('img_thumb').appendTo('.thumb_item:last');

};
reader.readAsDataURL(this.files[i]);
} 
Igor Martins
  • 2,015
  • 7
  • 36
  • 57
  • 1
    possible duplicate of [Javascript closure inside loops - simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – John Dvorak Oct 23 '13 at 18:01
  • Thanks... The problem is similir, but I can't apply this on my exempla.. :( – Igor Martins Oct 23 '13 at 18:05

2 Answers2

1

Why can't you apply the same technique pointed out in the comment?

reader.onload = (function(index)
                 {
                   return function (e)
                   {
                    $('.thumbs').append('<div class="thumb_item" id="c'+ index +'"></div>');
                    $('<img />').attr({'src': e.target.result}).addClass('img_thumb').appendTo('.thumb_item:last');
                   };
                 })(i);
Markku K.
  • 3,840
  • 19
  • 20
0

Thanks for all, I solved this way:

for (var i = 0; i < inp.files.length; i++) {

        var reader = new FileReader();

    // Closure to capture the file information.
    reader.onload = (function (theFile) {

     var count = i;
        return function (e) {
    $('.thumbs').append('<div class="thumb_item" id="c'+ count +'"></div>');
    $('<img />').attr({'src': e.target.result}).addClass('img_thumb').appendTo('.thumb_item:last');

};
})(i);
reader.readAsDataURL(this.files[i]);
}
Igor Martins
  • 2,015
  • 7
  • 36
  • 57