Javascript Loop rows and columns
Ok so i have a JSON file with开发者_JS百科 urls of 15 images in it. What i am trying to achieve is something like so...
1-2-3
4-5-6
7-8-9
10-11-12
13-14-15
So that I have 3 columns and 5 rows of images. I know i have to loop through the images to get them but how do i build them into rows so that there are 3 images in each row. Im using simple javascript not jquery or any other framework. Help would be really appreciated.
Edit: After re-reading the question and some of the comments, I believe the OP wants the images rendered in HTML and not simply placed in a two-dimensional array.
Given the following HTML:
<div id="images_container"></div>
You can take a JSON array with image data and do something like this:
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;
}
Note that 'data' can be replaced with actual data. I've given each image row a class of images-row
. Using this CSS class you could apply whatever styles you want to each row and each image in the row.
Note also that this code kind of assumes images of the same width and height. The logic won't break if the images are different sizes, but the presentation will look a little funky (that's where the CSS could come in).
I don't guarantee this will work (i'm tired right now), but something like this should do the trick:
// 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]]
精彩评论