0

I have a problem with looping over loading images:

var m = ["http://localhost:801/grillduck/img/mark1.jpg", "http://localhost:801/grillduck/img/mark2.jpg"];

for (i = 0; i < m.length; i++) {

  var img = $("<img />").attr('src', m[i]).load(function() {

      console.log($(this).height());
      console.log($(this).width());
      console.log(i); // PROBLEM here always return 2 instead of 0 then 1

      var content = $('<div class="ho-content" id="demo-content' + i + '">');
  });       

}

problem is that I need to get the correct value of I for the loop in order to create div but it always return 2.

Cheerio, Mark

Mark Thien
  • 1,108
  • 2
  • 22
  • 35
  • use `var i` and you allways override content – Dwza Jun 04 '14 at 08:33
  • 1
    The problem is explained in the dup, but in your case the simplest solution would be to use `$.each(m, function(i,img){...}` to avoid the issue altogether. – elclanrs Jun 04 '14 at 08:34
  • It is because you are not using `var i` – Ryan Jun 04 '14 at 08:35
  • not using var is not right. I put var there and it still the same. Can anyone please point out how can I implement Javascript closure inside loops in my case. I tried it but could get it to work – Mark Thien Jun 05 '14 at 02:50
  • I was using isotope metafizzy to sort images. after putting the
    into the img load function, it no longer sorting.
    – Mark Thien Jun 05 '14 at 04:01

0 Answers0