简体   繁体   中英

appendTo, multiple times

I've got a string within a variable:

var dot = '<div class="dot"></div>'

And I am trying to append it to some HTML, multiple times:

var number = 3; // this has come from an $('img').length; could be any number

$(dot * number).appendTo('.m-slide-ctrl');

The above obviously does not work, but I'm not sure how to approach something so simple. The number of times I would like the string to be written, would be dependent on the number of images (so using .length)

Any help would be great.

http://jsfiddle.net/tmyie/VE75U/

没有循环,仅追加一次

$(Array(number+1).join("<div class='dot'></div>")).appendTo('.m-slide-ctrl');

Simply use a for loop

for (var i=0;i<number;i++)
{
    $(dot).appendTo('.m-slide-ctrl');
}

DEMO

var slides = $('.m-slide img');        // Images in gallery
var n = slides.length;                 // count images
var dots = '';                         // HTML string

for(var i=0; i<n; i++){
    dots += '<div class="dot"></div>'; // Create buttons
}
$('.m-slide-ctrl').append( dots );     // Append them
                                       // outside the loop. Faster!

there's no reason to force jQuery to lookup your DOM several times for the same element, and for every iteration .append() to that element some HTML, if all of that can be done only once outside the loop. Makes sense? Also, the native for loop is faster than any other jQuery loop method.

Well if it comes from $('img').length , you could just do something like:

var $dotDivProto = $('<div class="dot"></div>');

$('.m-slide-ctrl').append($('img').map(function () {
    return $dotDivProto.clone();
});

Or simply parsing every time:

$('.m-slide-ctrl').append($('img').map(function () {
    return $('<div class="dot"></div>');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM