Chr*_*sMJ 0 javascript image while-loop
好的,我有一个 JSON 文件,其中包含 15 个图像的 URL。我想要实现的目标是这样的......
1-2-3
4-5-6
7-8-9
10-11-12
13-14-15
Run Code Online (Sandbox Code Playgroud)
这样我就有 3 列和 5 行的图像。我知道我必须遍历图像才能获取它们,但是我如何将它们构建成行,以便每行中有 3 个图像。我使用简单的 javascript,而不是 jquery 或任何其他框架。非常感谢您的帮助。
编辑:在重新阅读问题和一些评论后,我相信OP希望图像以HTML格式呈现,而不是简单地放置在二维数组中。
给定以下 HTML:
<div id="images_container"></div>
Run Code Online (Sandbox Code Playgroud)
您可以获取包含图像数据的 JSON 数组并执行如下操作:
var data = [
'http://farm4.static.flickr.com/3594/3498411074_f10d546f42_t.jpg',
'http://farm4.static.flickr.com/3364/3498396436_44bcdcc06f_t.jpg',
'http://farm4.static.flickr.com/3436/3356022463_cd53a9b57d_t.jpg',
'http://farm4.static.flickr.com/3422/3356840596_57f5da7842_t.jpg',
'http://farm4.static.flickr.com/3180/2776515140_b7cd27cf7e_t.jpg',
'http://farm4.static.flickr.com/3273/2758309734_48cfe16860_t.jpg',
'http://farm4.static.flickr.com/3156/2758267414_6320ce7bdd_t.jpg'];
var images = document.createElement("div");
images.setAttribute("id", "images");
var img;
for(var index = 0; index < data.length; index++) {
// If three images have been placed on a row,
// create a new row.
if (index % 3 === 0) {
row = document.createElement("div");
row.setAttribute("class", "images-row");
images.appendChild(row);
}
// replace 'data[index]' with the url of the image in each member of the array.
img = createImageElement(data[index]);
row.appendChild(img);
}
images.appendChild(row);
document.getElementById("images_container").appendChild(images);
// Creates an image element with the given url.
function createImageElement(url) {
img = document.createElement("img");
img.setAttribute("src", url);
img.setAttribute("alt", "image");
return img;
}
Run Code Online (Sandbox Code Playgroud)
请注意,“数据”可以替换为实际数据。我给每个图像行一个images-row. 使用这个 CSS 类,您可以将您想要的任何样式应用于每行和行中的每个图像。
另请注意,此代码假定图像具有相同的宽度和高度。如果图像大小不同,逻辑不会中断,但演示文稿会看起来有点时髦(这就是 CSS 可以发挥作用的地方)。