我有一个 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();
};
有什么建议吗?
最佳答案
如果您使用 jQuery 1.5,您可以利用它的 $.Deferred 实现:
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')
你的例子中的位不是真正的代码?该选择器将搜索 <fetching>
DOM 中的元素,这可能不是您想要的。
关于jquery - 在执行回调之前等待 .each() .getJSON 请求完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6462144/