如何将jQuery.when()与URL数组一起使用? [英] How to use jQuery.when() with an array of URLs?

查看:190
本文介绍了如何将jQuery.when()与URL数组一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何更改此示例

$.when(
   $.getScript( "/mypath/myscript1.js" ),
   $.getScript( "/mypath/myscript2.js" ),
   $.getScript( "/mypath/myscript3.js" ),
   $.Deferred(function( deferred ){
      $( deferred.resolve );
   })
).done(function() {
   //place your code here, the scripts are all loaded
});

当我不知道要加载并使用URL数组的确切脚本数量时?

when i don't know the exact number of scripts to load and use an array of URLs instead?

var urls = [
   '/url/to/script1.js',
   '/url/to/script2.js',
   '/url/to/script3.js',
   '/url/to/script4.js'
];

因为上面的示例是带有参数的函数调用,所以我不能利用像$.each()这样的循环,可以吗?另外,我了解Function.apply,但不知道如何适应从将简单参数数组传递给函数到将函数调用数组传递给函数.

As the above example is a function call with arguments I cannot utilize a loop like $.each(), can I? Also, I know about Function.apply, but don't know how to adapt from passing an array of simple arguments to a function to passing an array of function calls to a function.

推荐答案

您将使用.apply,然后通过arguments进行获取:

You'd use .apply and then get it with arguments:

var urls = [
   '/url/to/script1.js',
   '/url/to/script2.js',
   '/url/to/script3.js',
   '/url/to/script4.js'
];

var requests = urls.map(function(url){ return $.getScript(url); });
$.when.apply($, requests).then(function(){
    console.log(arguments); // logs all results, arguments is the results here
    return [].slice.call(arguments);
}).then(function(arr){
     // access as an array
});

这篇关于如何将jQuery.when()与URL数组一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆