I have the below json object and i want to loop through it and display the value in a div. My json object and the function to run it is below
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);
}
After i run this function i got 4 div created as expected but only the first child of the div has image shown and the other 3 has broken img, i try to debug and i see var a which is suppose to be the img name like myimg1.jpg and the result i got is
`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
What i want to get is like below so all div created will have the right link to the 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

imgsrc = $imgUrl = $imgUrl + a;. Not sure why you have assigned$imgUrlagain here.. Just keep it asimgsrc = $imgUrl + a;imgsrc = $imgUrl = $imgUrl+aIt has no meaning, just put the name in or the name + path