我有一个jquery.each
循环,从 json 请求中检索页面上具有特定类的所有元素的远程数据。一组元素是一组li
我想在之后使用另一个函数对标签进行排序li
元素已使用远程信息进行更新。
之后传入排序函数.each
循环不会对列表进行排序,因为项目尚未完成从 json 请求的加载。如果我将排序函数作为.complete
getJSON 请求的回调,但我只想对整个列表运行一次排序,而不是对每个项目运行一次。
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 中的元素,这可能不是您想要的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)