我有一个基于javascript / ajax的搜索系统,它调用文件并获取json数据
示例JSON数据
{"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}
以上JSON数据包含许多信息和图像名称
我只是解析json数据并在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>";
}
发生的事情是第一张图片被添加&amp;显示下一个跳过第三个添加并显示下一个跳过等。
如果每页的总搜索结果为10.仅显示5张图像
我尝试使用调试器来发现WTH正在进行中,我发现了一些奇怪的事情,并不知道究竟发生了什么。
当循环运行并且图像被添加img
变量设置为
在未添加图像的下一次迭代中,img
变量设置为
我已经检查了所有存在的图像并正确加载。 Chrome中的网络选项卡显示所有图像都已请求,状态为200
答案 0 :(得分:0)
您是按className='image'
选择元素,然后在<img>
的{{1}}标记上保留相同的类。选择器变量被更改并且新添加的“#”也被选中
这就是循环没有按预期工作的原因。
使用div
或在附加的document.querySelectorAll('div.image');
标记上添加其他类。
见this fiddle。我试过4个div,但它似乎有效。