简体   繁体   中英

JavaScript/JQuery/JSON append the 'i' of a for loop on an attribute

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);
}

In the first attempt, change the line to:

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

This is solution for you:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM