我有一个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请求。排序工作如果我传递排序函数作为 plete 回调的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 plete 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 = "something" 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 = "something"; $('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请求在执行回调之前完成
发布评论