1

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

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

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

4

2 回答 2

4

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

// 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");
});
于 2013-06-09T08:25:02.563 回答
1

$.map()如果我理解正确,可以用and简洁地编写执行您想要的代码$.when.apply(),如下所示:

// First scan someArr, calling $.getScript() and building 
// an array of up to 5 jqXHR promises.
var promises = $.map(someArr, function(obj, index) {
    return (index < 5) ? $.getScript(obj.fileName + ".js") : null;
});
// Now apply the promises to $.when()
$.when.apply(null, promises).done(function() {
    alert("done");
});

注:$.when.apply(null, promises)相当于:

$.when(jqXHR0, jqXHR1, jqXHR2, jqXHR3, jqXHR4);

其中jqXHR0等是jqXHR五个$.getScript()调用返回的对象。

于 2013-06-09T09:28:39.637 回答