简体   繁体   中英

Half images are shown/added results per page

I have a javascript/ajax based search system which calls a file and get json data

Sample JSON Data

{"id":["33","34","35","36","37","38","39","40","73"],"user_id":["16","16","16","16","16","16","16","16","17"],"name":["Ram Bachan","Ram Bachan","Ram Bachan","Ram Bachan","Ram Bachan","Ram Bachan","Ram Bachan","Ram Bachan","Amar Nath"],"date":["2016-03-21","2016-03-21","2016-03-21","2016-03-21","2016-03-21","2016-03-21","2016-03-21","2016-03-21","2016-03-21"],"outlet":["Rani Ka Bagh 1","Rani Ka Bagh 2","Rani Ka Bagh 3","Rani Ka Bagh 4","Rani Ka Bagh 5","Rani Ka Bagh 6","Rani Ka Bagh 7","Rani Ka Bagh 8","Hide Market 1"],"approved":["P","P","P","P","P","P","P","P","P"],"fileName":["409160.jpg","424831.jpg","785371.jpg","27401.jpg","527450.jpg","759700.jpg","540742.jpg","280322.jpg","959879.jpg"],"resultsCount":248,"currentPage":1,"lastPage":28}

Above JSON data contain many informaiton and name of images

I am simply parsing json data and adding images in the div

var jsonData = JSON.parse(ajax.responseText);
var img = document.getElementsByClassName("image");
for (var i = 0; i < jsonData['id'].length; i++) {
    console.log(i, jsonData['fileName'][i]);
    var imgName = jsonData['fileName'][i].split(",");
    img[i].innerHTML = "<div><img src='/user_data/" + jsonData["user_id"][i] + "/" + imgName[0] + "' class='image' /></div>";
}

What happening is First image is added & displayed next skips third added and displayed next skips so on.

If total search results per page is 10. Only 5 images is displayed

I tried using debugger to find WTH is going on and i found something weird don't no what exactly is happening.

When loop runs and image is added img variable sets to

在此处输入图片说明

On next iteration when image is not added img variable is set to

在此处输入图片说明

I have crossed checked all images exist and are loaded properly. Network tab in chrome shows all images are requested and there status is 200

You are selecting the elements by className='image' , then you are keeping the same class on the <img> tag in the div . The selector variable gets changed and newly appended '` also gets selected.
This is why loop is not working as expected.

Use either document.querySelectorAll('div.image'); or put a different class on img tags being appended.

See this fiddle . I have tried with 4 divs, but it seems to work.

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