【问题标题】:Loading multiple scripts and initiate the plugin at the last load加载多个脚本并在最后一次加载时启动插件
【发布时间】:2011-11-23 14:20:29
【问题描述】:

我正在通过get $.getScript加载一个插件的多个脚本,我应该只在最后一次加载脚本后启动插件,但我怎么知道循环何时到达最后一个?

// load multiple files.
var scripts = [
    'mode/xml/xml.js',
    'mode/css/css.js',
    'mode/javascript/javascript.js'
];

alert(scripts.length); // 3

for(var i = 0; i < scripts.length; i++) 
{
    $.getScript(http_root+'global/views/javascripts/codemirror/original/'+scripts[i], function() {

        alert(i); // this will alert number 3 for 3 times.

        if(i == scripts.length) // this means that the plugin will be initiated 3 times.
        {
            var editor = CodeMirror.fromTextArea(document.getElementById("code_content_1"), { 
                mode: "text/html", 
                theme: "eclipse",
                lineNumbers: true
            });
        }
    });

    alert(i); // this will alert the number from 0 to 2.
}

有什么想法吗?

【问题讨论】:

    标签: jquery ajax getscript


    【解决方案1】:

    将调用封装在闭包中,这样我就不会在每次迭代时更改变量。

    for(var i = 0; i < scripts.length; i++) 
    {
      (function(i) {
          $.getScript(http_root+'global/views/javascripts/codemirror/original/'+scripts[i], function() {
    
          if(i + 1 == scripts.length)
          {
            var editor = CodeMirror.fromTextArea(document.getElementById("code_content_1"), { 
                mode: "text/html", 
                theme: "eclipse",
                lineNumbers: true
            });
          }
        });
      })(i);  
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-23
      • 2014-01-22
      • 2014-04-20
      • 2015-06-13
      相关资源
      最近更新 更多