等待.each().getJSON请求在执行回调之前完成

编程入门 行业动态 更新时间:2024-10-23 23:29:28
本文介绍了等待.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请求。排序工作如果我传递排序函数作为 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请求在执行回调之前完成

本文发布于:2023-11-25 04:07:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628258.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:回调   getJSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!