如何控制在jQuery $(document).ready中被调用函数的顺序 [英] How to control the order of functions being called in jQuery $(document).ready
问题描述
我需要能够控制$(document).ready
事件中正在处理的项目的顺序.
这些是从多个文件加载的多个控件,所有控件都要求在ready
事件中调用.它们都启动对服务器(AJAX)的异步调用.只有完成所有步骤后,我才需要做一些额外的工作.
I need to be able to control the order of items being processed in the $(document).ready
event.
These are multiple controls, loaded from multiple files, all asking to be called in the ready
event. They all start an async call to the server (AJAX). Only after they are all done, I need to do some extra work.
对此有什么优雅的解决方案?
What would be the elegant solution for this?
推荐答案
异步请求 fire 按顺序执行,但以它们首先完成的顺序返回.因此,没有一种确定的方法可以强制它们同时结束,但是,您可以构建规则以仅在某些组返回后才运行代码.
Asynchronous requests fire in order, but will return in whatever order they complete in first. So there is not a sure fire way to force them to end at the same time, however, you can build rules to only run code after certain groups have returned.
例如,使用一组规则定义一个回调函数,并将其传递给所有ajax请求的每个success
回调.
For instance, define a callback function with a set of rules, and pass it to each success
callback for all of your ajax requests.
var completedObject = {};
function groupSuccessCallback() {
// Test for any combination of requirements
if ( completedObject.ajax1 && completedObject.ajax2 ) {
... // Do something that only requires 1 and 2
}
if ( completedObject.ajax1 && completedObject.ajax2 && completedObject.ajax3) {
... // Do something that requires all 3 being done
// your data is available at completedObject.ajax#
}
// Or test for _all_ entries for a dynamic count
var allComplete = true;
for(var i in completedObject) {
if ( completedObject.hasOwnProperty(i) && !completedObject[i] ) {
allComplete = false;
}
}
// Do whatchya need.
if (allComplete) {
alert("bb-b-bb-b-b-b-bbb... that's all folks!");
}
}
然后在成功功能中设置标志:
Then set the flags inside of your success functions:
// Ajax1
completedObject['anything'] = false; // instantiate a dynamic entry in the object or use an array if you can't use names.
$.ajax({
...,
...,
success: function(data) {
completedObject['anything'] = data || true;
groupSuccessCallback();
}
});
这篇关于如何控制在jQuery $(document).ready中被调用函数的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!