在执行回调之前等待 .each() .getJSON 请求完成
我有一个 jquery .each
循环,它从 json 请求中检索具有特定类的页面上所有元素的远程数据。一组元素是一组 li
标签,在使用远程信息更新 li
元素后,我想使用另一个函数对其进行排序。
在 .each
循环之后传入排序函数不会对列表进行排序,因为项目尚未完成从 json 请求的加载。如果我将排序函数作为 getJSON 请求的 .complete
回调传递,则排序有效,但我只希望排序对整个列表运行一次,而不是对每个项目运行一次。
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();
};
有什么建议吗?
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.
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();
};
Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用的是 jQuery 1.5,则可以利用其 $.Deferred 实现:
我假设示例中的
$('fetching')
位不是真正的代码?该选择器将在 DOM 中搜索
元素,这可能不是您想要的。If you're using jQuery 1.5, you could take advantage of its $.Deferred implementation:
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() 之前获取要执行的提取总数。然后附加 .complete 回调,在该回调中,您首先增加已完成请求的数量,并且仅当已完成的数量等于要执行的总数时才进行排序。原则上,您应该仅在所有 ajax 调用完成后才运行排序...K
Try to get the total number of fetches to be be performed before fireing each(). Than attach the .complete callback in which you first increase some count of completed requests and sort only if the number of completed equals to the total number to be performed. In principle, you should run sort only after all ajax called has finished...K