jQuery each with timeout

2019-07-25 04:42发布

I have the following function which runs OK except for one thing. There is no consequence in what it appends first.

(function biograf(){
  var placeholder = $('#top-imageholder');
  $('ul#biomenu > li').each(function(){
    var obj = $(this);
    var pageLink = obj.find('a:first').attr('href');
    $.get(pageLink, function(data) {
      placeholder.append( $(data).find('#top-imageholder').html() );
      placeholder.append( $(data).find('#top-imageholder').siblings('ul') );
    });
  });
})();

I would like the function to append the placeholder in the order my list items are placed in the #biomenu.

It does this 90% of the time, but once in a while it appends in different orders.

Any suggestions?

2条回答
男人必须洒脱
2楼-- · 2019-07-25 05:26

Well got it to work with the following code:

(function biograf(){
  var placeholder = $('#top-imageholder');
  var item = $('ul#biomenu > li');
  var index = 0;

  (function loop(){
    setTimeout(function(){
      var pageLink = item.eq(index).find('a:first').attr('href');
      if( pageLink != undefined ){
        $.get(pageLink, function(data) {
          placeholder.append( $(data).find('#top-imageholder').html() );
          placeholder.append( $(data).find('#top-imageholder').siblings('ul') );
        });     
        index++;
        loop();
      }
    });
  })();
})();

I'm not sure if this is the most optimal way, or if the code could be tweeked. But it works! :)

Thanks for all the replies though!

查看更多
成全新的幸福
3楼-- · 2019-07-25 05:30

Order results with $.when (untested code):

(function (){

  var placeholder = $('#top-imageholder');
  var promises = [];

  $('ul#biomenu > li').each(function(){
    var obj = $(this);
    var pageLink = obj.find('a:first').attr('href');
    promises.push($.get(pageLink));
  });

  $.when.apply(null, promises).done(function() {
    $.each(arguments, function(data) {
      placeholder.append( $(data).find('#top-imageholder').html() );
      placeholder.append( $(data).find('#top-imageholder').siblings('ul') );
      return true;
    });
  });

})();
查看更多
登录 后发表回答