jQuery使用'for'来复制div

时间:2022-04-10 22:36:23

I want to create a number of divs so they fill a current window size. So far i have got it to make it once, but cant get this to repeat. I am putting them inside another div, so when the containing div reaches the height of the window it stops making them.

我想创建一些div,以便填充当前窗口大小。到目前为止,我已经做到了一次,但不能重复这一点。我把它们放在另一个div中,所以当包含的div达到窗口的高度时,它就会停止制作它们。

$(document).ready(function() {
    var winHeight = $(window).height(),
        divHeight = $('div.container').height(),
        html = $('<div class="line"></div>');

    for (i = 1, l = 10; i < l; i++) {
        $('div.container').append(html); }

How do substitute the i and l for the variables winHeight and divHeight? Many thanks.

如何用i和l代替变量winHeight和divHeight?非常感谢。

2 个解决方案

#1


5  

Assuming that all lines have the same height (let me know), you could this :

假设所有线都有相同的高度(让我知道),你可以这样:

var html, winHeight, lineHeight, howManyLines;
html = '<div class="line"></div>';
winHeight = $(window).height();
// appends one line in order to retrieve its actual height
lineHeight = $(html).appendTo('div.container').height();
// calculates the required number of lines to fill the window
howManyLines = Math.floor(winHeight / lineHeight);
// appends missing lines
$('div.container').append(
    new Array(howManyLines).join(html)
);

#2


5  

don't create html as a jQuery object, just create the html template

不要将html创建为jQuery对象,只需创建html模板即可

html = '<div class="line"></div>';

other wise it is like you are trying to append the same element in the loop, another solution is to use clone()

另外,它就像你试图在循环中追加相同的元素,另一个解决方案是使用clone()

html = $('<div class="line"></div>');

then

然后

$('div.container').append(html.clone());

#1


5  

Assuming that all lines have the same height (let me know), you could this :

假设所有线都有相同的高度(让我知道),你可以这样:

var html, winHeight, lineHeight, howManyLines;
html = '<div class="line"></div>';
winHeight = $(window).height();
// appends one line in order to retrieve its actual height
lineHeight = $(html).appendTo('div.container').height();
// calculates the required number of lines to fill the window
howManyLines = Math.floor(winHeight / lineHeight);
// appends missing lines
$('div.container').append(
    new Array(howManyLines).join(html)
);

#2


5  

don't create html as a jQuery object, just create the html template

不要将html创建为jQuery对象,只需创建html模板即可

html = '<div class="line"></div>';

other wise it is like you are trying to append the same element in the loop, another solution is to use clone()

另外,它就像你试图在循环中追加相同的元素,另一个解决方案是使用clone()

html = $('<div class="line"></div>');

then

然后

$('div.container').append(html.clone());