简体   繁体   English

JavaScript/JQuery/JSON 在属性上附加 for 循环的“i”

[英]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.我有 4 个图片位置保存在一个名为 img0、img1、img2 和 img3 的 JSON 文件中。 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.我从每个 AJAX 调用的文件中获取数据(getJSON,保存在 var receivedProduct 中),之后我只是将它们发送到我页面上图像的“src”部分。

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".但是如果我想从中创建一个循环(因为重复的代码看起来不太好),我会收到错误“未定义”或“未找到 404”。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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