本文介绍了$ .when.done回调不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码具有错误的语法错误。可能是因为我使用的是'for'或某事。
The following code has a bad syntax error. Probably because I'm using 'for' or something.
$.when(
for (var i=0; i < 5; i++) {
$.getScript( "'" + someArr[i].fileName + ".js'");
}
$.Deferred(function( deferred ) {
$( deferred.resolve );
})
).done(function() {
alert("done");
});
我试图调用几个脚本,然后当trey都加载我想警报
I'm trying to call couple of scripts and then when trey are all loaded I want to an alert to show.
推荐答案
具有更改的已注释(但未测试)解决方案位于
A commented (but untested) solution with the changes is below
// When takes a promise (or list of promises), not a random string of javascript
$.when((function() {
// First we need to define a self resolving promise to chain to
var d = $.Deferred().resolve();
for ( var i = 0; i < 5; i++ ) {
// Trap the variable i as n by closing it in a function
(function(n) {
// Redefine the promise as chaining to itself
d = d.then(function() {
// You can *return* a promise inside a then to insert it into
// the chain. $.getScript (and all ajax methods) return promises
return $.getScript( someArr[n].fileName + '.js' );
});
// Pass in i (becomes n)
}(i));
}
return d;
// self execute our function, which will return d (a promise) to when
}())).then(function() {
// Note the use of then for this function. done is called even if the script errors.
console.log( 'done' );
});
如果您有选择,更简单的只是
If you have the option, something much simpler is just
$.when(
$.getScript( 'fileName1.js' ),
$.getScript( 'fileName2.js' ),
$.getScript( 'fileName3.js' ),
$.getScript( 'fileName4.js' )
).then(function() {
alert("done");
});
这篇关于$ .when.done回调不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!