开发者

jQuery append an element more than once

I'm curr开发者_如何学运维ently trying to add n number of divs to the bottom of the body, however using this code:

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

for(i=0; i<12; i++) {
    $('body').append(star); 
}

results in just one div being appended to the bottom of the body. I'm guessing this is because the content of the body is not being refreshed between each iteration of the for loop, but can't figure out how to best to solve it.


Rather than executing 12 DOM modifications, why not multiply the string and then use just one .append() call?

String.prototype.times = function(n) {
    return Array.prototype.join.call({length: n+1}, this);
};

var star = '<div class="star" />'.times(12);
$('body').append(star);

jsFiddle


Fix for your original method

If you want to stay with your method, you'll need to call the $ function inside the loop so that a distinct jQuery object is created on each iteration. I'm guessing this is slower, but it'd work.

star = '<div class="star" />';
var body = $('body');

for ( i = 0; i < 12; i++ ) {
    body.append($(star));
}

jsFiddle


$('body').append(new Array(13).join('<div class="star" />'));


Try this

var star = '<div class="star" />SomeTest</div>';

for(i=0; i<12; i++) {
    $('body').append(star); 
}


It should be noted that using FOR loop is worse than iterating with jquery .each() function, as FOR loop is not asynchronous and therefore much much slower on bigger scale, since each() instances run side by side, when FOR loop waits for each iteration to complete before continueing to next iteration.

(Can't just comment because of 50 rep requirement.)


$(document).ready(function() {
    star = '<div class="star" />';
    var body = $('body');

    for ( i = 0; i < 12; i++ ) {
        body.append($(star));
    }
});
.star {  border: 1px solid black; height: 20px; width: 100px;margin-bottom:1px }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜