jQuery each with timeout

2019-07-25 04:55发布

问题:

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?

回答1:

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!



回答2:

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;
    });
  });

})();