gpt4 book ai didi

javascript - $.when.done 回调不起作用

转载 作者:行者123 更新时间:2023-11-30 08:52:04 24 4
gpt4 key购买 nike

以下代码有一个错误的语法错误。可能是因为我正在使用“for”之类的东西。

$.when(
for (var i=0; i < 5; i++) {
$.getScript( "'" + someArr[i].fileName + ".js'");
}
$.Deferred(function( deferred ) {
$( deferred.resolve );
})
).done(function() {
alert("done");
});

我正在尝试调用几个脚本,然后当 trey 全部加载时我想显示一个警报。

最佳答案

下面是带有更改的评论(但未经测试)的解决方案

// 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' );
});

如果你有选择,更简单的事情就是

$.when(
$.getScript( 'fileName1.js' ),
$.getScript( 'fileName2.js' ),
$.getScript( 'fileName3.js' ),
$.getScript( 'fileName4.js' )
).then(function() {
alert("done");
});

关于javascript - $.when.done 回调不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17007640/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com