2

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?

2 Answers 2

2
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);
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

No i haven't. I'm using dot notation on the element.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.