好吧,所以我有一個JSON文件的15個圖像在其中的網址。我試圖實現的是這樣的...Javascript循環行和列
1-2-3
4-5-6
7-8-9
10-11-12
13-14-15
這樣我有3列和5行圖像。我知道我必須通過圖像循環來獲取它們,但我如何將它們構建成行,以便每行有3個圖像。我使用簡單的JavaScript而不是jQuery或任何其他框架。幫助將非常感激。
好吧,所以我有一個JSON文件的15個圖像在其中的網址。我試圖實現的是這樣的...Javascript循環行和列
1-2-3
4-5-6
7-8-9
10-11-12
13-14-15
這樣我有3列和5行圖像。我知道我必須通過圖像循環來獲取它們,但我如何將它們構建成行,以便每行有3個圖像。我使用簡單的JavaScript而不是jQuery或任何其他框架。幫助將非常感激。
我不保證這會工作(我累了現在),但這樣的事情應該做的伎倆:
// let's say that arr == [0,1,2,3,4,5,6,7,8]
result = []
for(i=0; i<=arr.length-step; i+=step)
{
row = []
for(j=i; j<i+step && j<arr.length; i++)
row.push(arr[j]); // or arr[j].image_url or whatever you need
result.push(row);
}
// result is now something like [[0,1,2],[3,4,5],[6,7,8]]
編輯:後重新閱讀的問題和一些評論,我相信OP希望圖像呈現在HTML中,而不是簡單地放置在一個二維數組。
考慮下面的HTML:
<div id="images_container"></div>
你可以把一個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;
}
注意該「數據」可以與實際被替換數據。我已給每個圖像行一個images-row
類。使用這個CSS類,您可以將所需的任何樣式應用於每行和每行中的圖像。
還請注意這種代碼假設圖像的寬度和高度相同。如果圖像大小不同,邏輯將不會中斷,但演示文稿看起來有點時髦(這是CSS可以進入的地方)。
通過'JSON文件'你是指一個JSON數組還是一個JSON對象?你可以添加一個JSON樣本嗎? – 2010-11-28 21:39:20
對不起,它的JSON數組內有很多對象 – ChrisMJ 2010-11-28 21:41:41
您是否嘗試創建具有三列和五行的表,然後附加到文檔中,或者在數組中有這個? – 2010-11-28 22:08:51