Ryan
Ryan

Reputation: 14659

jQuery .load() within a for loop

I send an ajax request to my server. I then receive an object. The object looks likes this:

{
    "payload": {
        "result": [
            "http://example.com/img1.jpg",
            "http://example.com/img2.jpg",
            "http://example.com/img3.jpg",
            "http://example.com/img4.jpg",
            "http://example.com/img5.jpg"
        ]
    }
}

I then traverse the object using a for loop

if (typeof response.payload.result == 'object') {
    var ln = response.payload.result.length;
    var i;
    if (ln > 0) {
        for (i = 0; i < ln; i++) {
              /* this shows i was increased for every iteration */
              console.log(i);
          var current_img = response.payload.result[i];
          var img = $("<img />").attr('src', current_img)
           .load(function () {
                  console.log(i);
                  /* this logs the last iteration 4 times */
                $("#product-images").append(img);
          });
        }
    }
}

My problem is that only (1) image element is being created. The single element being appended to the DOM after this code executes is the value of the last element in the array. Why is jQuery.load() only being called on the last iteration?

Upvotes: 2

Views: 245

Answers (2)

Kelsadita
Kelsadita

Reputation: 1038

I guess u have missed the semicolon for this line

var img = $("<img />").attr('src', current_img)

and you have not specified the selector of the element in which you want to load the image.

Upvotes: 0

Niccol&#242; Campolungo
Niccol&#242; Campolungo

Reputation: 12040

if (typeof response.payload.result == 'object') {
    var ln = response.payload.result.length;
    var i;
    if (ln > 0) {
        for (i = 0; i < ln; i++) {
            (function (n) {
                var current_img = response.payload.result[i];
                var img = $("<img />").attr('src', current_img)
                    .load(function () {
                    console.log(n);
                    $("#product-images").append(img);
                });
            })(i);
        }
    }
}

Upvotes: 2

Related Questions