0

是否可以根据以下条件调用外部 javascript 文件,例如

switch (VCheck) {
    case "1":
        Call "1.js"
        break;
    case "2":
        Call "2.js"
        break;
    case "3":
        Call "3.js"
        break;
    case "4":
        Call "4.js"
        break;
    case "5":
        Call "5.js"
        break;
    case "0":
        Call "Default.js"
        break;
    default: alert("Server Error - No Data!");
}

如果是这样,请您协助提供正确的语法。

4

1 回答 1

2

您应该使用 require.js,它以更优雅的语法完全满足您的需求。

http://requirejs.org/

如果您的“调用”指令执行异步加载,您也可以通过这种方式分解您的代码:

function Call(VCheck, callback)
{
    callback = callback || function(data) {};

    var data = ["Default", "1", "2", "3", "4", "5"];
    if (VCheck < 0 || VCheck > data.length - 1) { return alert("Server Error - No Data!"); }

    var script = document.createElement("script");
    script.id = "data" + Math.ceil(Math.random() * 0xffffff).toString(16);
    script.async = true;
    script.type = "text/javascript";
    script.src = data[VCheck] + ".js";

    var head = document.getElementsByTagName("head")[0];
    head.insertBefore(script, head.firstChild);

    var img = new Image();
    img.onload = function()
    {
        //your data here
        console.log(document.getElementById(script.id).innerHTML);

        var data = document.getElementById(script.id).innerHTML;
        callback.call(null, data);
    };
    img.src = script.src;
}

或者,如果您使用 jQuery 的getScript

$.getScript(data[VCheck] + ".js", function(data)
{
   //your data here
   console.log(data);
});
于 2013-01-29T09:37:51.320 回答