2

我想备份,删除列表中的每个项目,并在 1 秒后追加每个项目。

我正在尝试这样:

var backup = $('#rGallery').html();
$('#rGallery li').remove();
console.log($(backup).filter('li').length); /* it logs like 135 */
$(backup).filter('li').each(function(){
    var the = $(this);
    var timeout = setTimeout(function(){
        console.log(the.html()); /* it logs the html, but all at the same time*/
        $('#rGallery').append('<li>'+the.html()+'</li>');

        /*return*/
    },1000);
});

它的工作,项目被删除,然后再次追加,问题是它们都在 1 秒后被追加。而不是每个都从前一个等待 1 秒。

我在这里想念什么?

4

2 回答 2

6

因为您要告诉它们都在一秒钟内运行,所以它们不会被添加到某个魔术队列中并排队等待开始计数。

$(backup).filter('li').each(function(index){  //added index here
    var the = $(this);
    var timeout = setTimeout(function(){
        console.log(the.html()); /* it logs the html, but all at the same time*/
        $('#rGallery').append('<li>'+the.html()+'</li>');

        /*return*/
    },1000*(index+1)); //multiplied it here
});
于 2013-05-25T12:08:47.277 回答
3

setTimeout没有阻塞;它安排超时,然后继续。因此,下一次迭代each()立即发生,它将下一个元素安排在完全相同的时间(等等)。

因此,您应该像这样更改代码(一种方法),每 1000 毫秒运行一次函数,将下一个元素添加到backup.

var backup = $('#rGallery li');
var i = 0;
$('#rGallery li').remove();

var interval = setInterval(function () {
    if (i === backup.length) {
        clearInterval(interval);
    } else {
        var the = $(backup).eq(i);

        $('#rGallery').append('<li>'+the.html()+'</li>');
    }

    i++;
}, 1000);
于 2013-05-25T11:57:16.153 回答