以下代码:
var images = [/*array with images*/];
var nofImages = images.length;
$(document).ready(function(){
var docheight = $('.main_insidem').height();
var docwidth = $('.main_insidem').width();
var he = Math.round((docheight/120));
var wi = Math.round((docwidth/115));
var total = (he*wi);
var container = document.getElementById('slidesContainer');
for (var i=0;i<nofImages;i++) {
var slide = document.createElement('div');
slide.className="slide";
var img = document.createElement('img');
img.src=images[i];
img.className="image"+i;
slide.appendChild(img);
container.appendChild(slide);
}
})
节目:
<div class='main_insidem' style="height:500px;">
<div id="slidesContainer">
<div class="slide"><img src="1.png" class="image0"></div>
<div class="slide"><img src="2.png" class="image1"></div>
<div class="slide"><img src="3.png" class="image2"></div>
<div class="slide"><img src="4.png" class="image3"></div>
.
.
.
.
</div>
</div>
但我需要:
<div class='main_insidem' style="height:500px;">
<div id="slidesContainer">
<div class="slide"><img src="1.png" class="image0"> <img src="2.png" class="image1">.. and and so on until the value in var total is reached</div>
<div class="slide"><img src="..png" class="image.."> <img src="...png" class="image">.. and and so on until the value in var nofImages is reached</div>
.
.
.
.
</div>
</div>
我该怎么做?
非常感谢
答案 0 :(得分:1)
试试这个,
var images = [/*array with images*/],
nofImages = images.length,
imagesPerDiv = 2;
$(document).ready(function(){
var docheight = $('.main_insidem').height(),
docwidth = $('.main_insidem').width(),
he = Math.round((docheight/120)),
wi = Math.round((docwidth/115)),
total = (he*wi),
container = $('#slidesContainer');
loopCNT = Math.ceil(nofImages / imagesPerDiv);
for (var i=0;i<=loopCNT;i++) {
var slide = document.createElement('div');
slide.className="slide";
for (var j=i-1*imagesPerDiv;j<=imagesPerDiv;i++) {
var img = document.createElement('img');
img.src=images[j];
img.className="image"+j;
slide.appendChild(img);
j++;
}
container.appendChild(slide);
}
})
你也可以削减很多脂肪,并“正确”使用jQuery并将整个内容缩短到以下内容:
var images = [/*array with images*/],
nofImages = images.length,
imagesPerDiv = 2;
$(function() {
loopCNT = Math.ceil(nofImages / imagesPerDiv);
for (var i=0;i<=loopCNT;i++) {
var slide = $('<div />', { class: 'slide' });
for (var j=i-1*imagesPerDiv;j<=imagesPerDiv;i++) {
$('<img />', { class: "image"+j, src: images[j] }).appendTo(slide);
j++;
}
$('#slidesContainer').append(slide);
}
})
答案 1 :(得分:0)
看看这个:http://jsfiddle.net/AfNUS/2/
这是不对的,它在第一组图像之前不断创建一个空白div它可以满足您的需要,如果你能解决为什么它会添加空白div那么它将是完美的:)