0

I have 4 picture locations saved in a JSON file called img0, img1, img2 and img3. I am getting the data from the file per AJAX call (getJSON, saved in the var receivedProduct) and after that i am just sending them to the "src" section of the images on my page.

If i use this everything works fine:

$("#img0").attr("src", receivedProduct.img0);
$("#img1").attr("src", receivedProduct.img1);
$("#img2").attr("src", receivedProduct.img2);
$("#img3").attr("src", receivedProduct.img3);

but if i want to make a loop out of it (because duplicate code just doesn't look nice) im getting the error "undefined" or "404 not found".

This is what i tried:

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

     $("#img" + [i]).attr("src", receivedProduct.img + [i]);
}

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

     var newImg = "receivedProduct.img"+i; 
     $("#img" + [i]).attr("src", newImg);
}

2 Answers2

1

In the first attempt, change the line to:

    $("#img" + i).attr("src", receivedProduct["img" + i]);
    //        ^^^                            ^^^^^^^^^^^
trincot
  • 317,000
  • 35
  • 244
  • 286
0

This is solution for you:

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

     $("#img" + i).attr("src", receivedProduct[".img" + i]);
}
Milos Gak
  • 21
  • 1
  • 4