jQuery each with timeout

三世轮回 提交于 2019-12-11 14:47:11

问题


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

})();


来源:https://stackoverflow.com/questions/14480359/jquery-each-with-timeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!