等待.each().getJSON请求在执行回调之前完成 [英] Wait for .each() .getJSON request to finish before executing a callback

查看:327
本文介绍了等待.each().getJSON请求在执行回调之前完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个jquery .each 循环,它从一个json请求中检索一个页面上所有元素的远程数据。一组元素是一组 li 标签,我想使用 li 元素后的另一个函数已经用远程信息更新。

I have a jquery .each loop that retrieves remote data from a json request for all the elements on a page with a certain class. One set of the elements is a group of li tags that I would like to sort using another function after the li element has been updated with the remote information.

.each 循环后,传递排序函数不会对列表排序,因为项目尚未完成加载从json请求。排序工作如果我传递排序函数作为 .complete 回调的getJSON请求,但我只想排序运行一次整个列表,而不是每个项目。

Passing in the sort function after the .each loop does not sort the list because the items have not finished loading from the json request. The sorting works If I pass in the sort function as a .complete callback for the getJSON request but I only want the sort to run once for the whole list, not for each item.

fetch_remote_data(function(){sort_list_by_name();});

function fetch_remote_data(f){
jQuery('.fetching').each(function(){
   var oj = this;
   var kind = this.getAttribute('data-kind');
   var url = "http://something.com"
   jQuery.getJSON(url, function(json){
       $(oj).text(json[kind]);
       $(oj).toggleClass('fetching');
   });
});
 if (typeof f == 'function') f();
};

有任何建议吗?

推荐答案

如果你使用jQuery 1.5,你可以利用它的$ .Deferred实现:

If you're using jQuery 1.5, you could take advantage of its $.Deferred implementation:

function fetch_remote_data(f) {
  var requests = [],
      oj = this,
      url = "http://something.com";

  $('fetching').each(function() {
    var request = $.getJSON(url, function(json) {
      $(oj).text(json['name']);
      $(oj).toggleClass('fetching');
    });

    requests.push(request);
  });

  if (typeof f === 'function') 
    $.when(requests).done(f);
}

// No need to wrap this in another function.
fetch_remote_data(sort_list_by_name);

我假设 $('fetching') bit在你的例子中不是真正的代码?该选择器将在DOM中搜索< fetching> 元素,这可能不是您想要的。

I'm assuming the $('fetching') bit in your example isn't real code? That selector would be searching for <fetching> elements in the DOM, which probably isn't what you want.

这篇关于等待.each().getJSON请求在执行回调之前完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆