我有下面的 json 对象,我想循环它并在 div 中显示该值。 我的 json 对象和运行它的函数如下
photos = [{"photo1":"myimage1.jpg",
"photo2":"myimg2.jpg",
"photo3":"myimg3.jpg",
"photo4":"myimg4.jpg",}]
function showPhotoOnLoad(photos,$imgUrl){
var $photoData = photos;
var photoLength = Object.keys($photoData[0]).length;
var i, key;
var $containerWidth = 110;
//alert(photoLength);
if(photoLength >0){
$(".mycarousel-container").show();
for (i in $photoData) {
for (key in $photoData[i]) {
a = $photoData[i][key];
imgsrc = $imgUrl = $imgUrl+a;
var div = $("<div class='mycarousel' style='left:"+left+"px'></div>");
var imgPreview = "<img class='myimg' src="+imgsrc+">";
div = div.append(imgPreview);
$(".carouser-inner").append(div);
left = left+$containerWidth;
}
}
}
//console.log($imgUrl);
}
运行此函数后,我按预期创建了 4 个 div,但只有该 div 的第一个子级显示了图像,其他 3 个已损坏 img,我尝试调试并看到 var a
假设是 img
名称,如 myimg1.jpg
,我得到的结果是
`a=myimg1.jpg` //at first iteration of the for loop which make the img display correctly,
`a=myimg1.jpgmyimg2.jpg` //at the second iteration
`a=myimg1.jpgmyimg2.jpgmyimg3.jpg` //at the third iteration
`a=myimg1.jpgmyimg2.jpgmyimg3.jpgmyimg4.jpg` //at the last iteration
我想要得到的内容如下所示,因此创建的所有 div 都将具有指向 img
的正确链接
`a=myimg1.jpg` //at the first iteration
`a=myimg2.jpg` //at the second iteration
`a=myimg3.jpg` //at the third iteration
`a=myimg4.jpg //at the last iteration
最佳答案
Problem is with imgsrc = $imgUrl = $imgUrl + a;
这是工作片段
var photos = [{"photo1":"myimage1.jpg",
"photo2":"myimg2.jpg",
"photo3":"myimg3.jpg",
"photo4":"myimg4.jpg"}];
showPhotoOnLoad(photos,"imageurl");
function showPhotoOnLoad(photos,$imgUrl){
var $photoData = photos;
var photoLength = Object.keys($photoData[0]).length;
var i, key;
var $containerWidth = 110;
//alert(photoLength);
if(photoLength >0){
$(".mycarousel-container").show();
for (i in $photoData) {
for (key in $photoData[i]) {
a = $photoData[i][key];
imgsrc = "a="+a;
var div = $("<div class='mycarousel' style='left:20px'></div>");
var imgPreview = "<img class='myimg' src="+imgsrc+">";
div = div.append(imgPreview);
$(".carouser-inner").append(div);
console.log(imgsrc);
// left = left+$containerWidth;
}
}
}
//console.log($imgUrl);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
关于javascript - 如何循环遍历json数组以获取javascript中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38549504/