javascript - 从外部文件调用外部 JS 函数

标签 javascript function

好的,情况是这样的。

我在页面中嵌入了一个语言切换链接,它将 URL 的字符串从 -eng.shtml 更改为 -fra.shtml 以及别名值。

现在基本上在 header 中我调用了两个脚本:

<script type="text/javascript" src="/js/langDB.js"></script>
<script type="text/javascript" src="/js/langToggle.js"></script>

LangToggle.js 在 langDB.js 中有一个函数,但是当调用编程到 langDB.js 中的函数时,它并没有按预期工作,它的功能应该是将变量值从一个更改为另一个。

切换代码:

function js_changeit(){

    //Get the current page full URL 
        var mainName = String(window.location);

    //Base name
        var slash = mainName.lastIndexOf("/");  
        var dot = mainName.lastIndexOf(".");
        var quest = mainName.lastIndexOf("?");
        var name = mainName.substring(slash+1,dot);
        var ext = mainName.substring(dot,mainName.length);

    //Remove the _f is it exists
        var lang = name.substring(name.length-3,name.length);

    //Detect the site sections, get the current site title and the site primary alias strings
        var SiteSection = mainName.split("/");
        var currentAlias = SiteSection[3];
        var currentSite = SiteSection[2];

    //Split the url from Site to the end Alias section
        var siteSectionAlias = "http://" + currentSite + "/" + currentAlias + "/";
        var SectionaAlias = mainName.split(siteSectionAlias)
        var htmlFullDocFilename = SectionaAlias[1];

    //Extract the filename without the extension
        var shtmlLastPos = htmlFullDocFilename.lastIndexOf(".shtml");
        var docTitle = htmlFullDocFilename.substring(0,shtmlLastPos-4);     

    //Alias Toggles, when an alias is detected in the conditional list, switch to the other.


    langToggle();

    // Main Page
        if (lang != "eng") {
            window.open("http://" + currentSite + "/" + currentAlias + "/" + docTitle + "-eng" + ext, "_self");
        } else {
            window.open("http://" + currentSite + "/" + currentAlias + "/" + docTitle + "-fra" + ext, "_self");
        }
    }

langDB.js 中的函数:

function langToggle() {
    switch(currentAlias) {
    //Switch the variable from English to French and vice versa depending on the current page's URL string when the toggle js link is clicked
        //If ENGLISH switch the variable to French
        case "about-us": 
            currentAlias = "a-notre-sujet"; break;
        //If FRENCH switch the variable to French
        case "a-notre-sujet": 
            currentAlias = "about-us"; break;
        /* -------------------------------------[ See the first two comments ]---------------------------------- */
        case "facilities-and-security": 
            currentAlias = "installations-et-securite"; break; 
        case "installations-et-securite": 
            currentAlias = "facilities-and-security"; break;
        /* -------------------------------------[ See the first two comments ]---------------------------------- */
        case "offenders": 
            currentAlias = "delinquants"; break; 
        case "delinquants": 
            currentAlias = "offenders"; break;
        /* -------------------------------------[ See the first two comments ]---------------------------------- */
        case "you-and-csc": 
            currentAlias = "scc-et-vous"; break; 
        case "scc-et-vous": 
            currentAlias = "you-and-csc"; break;
        /* -------------------------------------[ See the first two comments ]---------------------------------- */
        case "connecting": 
            currentAlias = "etablir-des-liens"; break; 
        case "etablir-des-liens": 
            currentAlias = "connecting"; break;
        /* -------------------------------------[ See the first two comments ]---------------------------------- */
        case "resources": 
            currentAlias = "ressources"; break; 
        case "ressources": 
            currentAlias = "resources"; break;
        /* -------------------------------------[ See the first two comments ]---------------------------------- */
        case "international-transfers": 
            currentAlias = "transferements-internationaux"; break; 
        case "transferements-internationaux": 
            currentAlias = "international-transfers"; break;
        /* -------------------------------------[ See the first two comments ]---------------------------------- */
        case "educational-resources": 
            currentAlias = "ressources-pedagogiques"; break; 
        case "ressources-pedagogiques": 
            currentAlias = "educational-resources"; break;
        /* -------------------------------------[ See the first two comments ]---------------------------------- */
        case "cfp": 
            currentAlias = "pfc"; break; 
        case "pfc": 
            currentAlias = "cfp"; break;
    }
}

每当我单击语言切换链接时,IE 都会给我一个“currentAlias”未定义的错误,基本上变量的值似乎没有加载到从外部脚本调用的函数中...

我不太确定我做错了什么......

最佳答案

when ever I'll click the language toggle link IE will give me an error that "currentAlias" is undefined...

那是因为 currentAliasjs_changeit 函数中的一个局部变量langToggle 无法访问 js_changeit 内的局部变量。

如果您的代码确实需要访问它,并且这些确实必须是单独的文件,您必须将 js_changeit 放入全局命名空间(window 上的一个属性):

window.currentAlias = currentAlias;

...然后从那里使用它。并且您需要确保 js_changeitlangToggle 之前运行,以便将其放在 window 上的代码运行。

(我说“全局变量”和“window 上的属性”可以互换,因为所有全局变量都是单个 [未命名] JavaScript 全局对象的属性,并且在浏览器上可以从全局变量 window 访问该对象 [window 是一个指向它所属对象的属性]。)

但是如果 langToggle 需要访问它,一些重构可能是合适的,尤其是这样您就可以避免添加更多的全局符号。

抱歉,刚刚再次查看您的代码,发现 js_changeit 调用 langToggle 。因此,更好的解决方案是 js_changeitcurrentAlias 作为参数传递给 langToggle。不需要全局变量。

所以在 js_changeit 中更改这一行:

langToggle();

到:

currentAlias = langToggle(currentAlias);

然后更改 langToggle,使其接受 currentAlias 作为参数并返回更新后的值。

你误入歧途的一点是,函数不会从它被调用的范围继承变量,而是从它定义的范围继承它们.所以 currentAlias 对于 langToggle 不存在,因为它没有在声明 langToggle 的范围内声明。

让我们举一个更简单的例子:

function foo() {
    var answer = 42;

    bar();
}

function bar() {
    console.log(answer); // <== Error, `answer` is not defined
}

barfoo 调用,但不继承 foo 的变量。如果 foo 想要与 bar 通信,它通常会将其作为参数传递:

function foo() {
    var answer = 42;

    bar(answer);
}

function bar(a) {
    console.log(a); // This is fine
}

那么,如果我们调用 foobar 将记录“42”。

类似地,如果 bar 需要将某些东西传回给 foo,它通常会通过返回一个值来实现:

function foo() {
    var answer = 42;
    var b;

    b = bar(answer);
    console.log(b);
}

function bar(a) {
    console.log(a);
    return a * 2;
}

现在,如果我们调用 foobar 将记录“42”,而 foo 将记录“84”。

foobar 可以通过其他方式共享信息(对象属性、闭包),但如果您不熟悉这些内容,那么现在就可以继续学习了。 :-)

关于javascript - 从外部文件调用外部 JS 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13201041/

相关文章:

javascript - 如何防止 Backbone.js 中的路由?

javascript - AngularJS 创建动态模板

javascript - 如何将插入符放在空的 DOM 元素节点中

javascript - 检查数组中的空元素

function - 自动完成通过 Google 表格中的脚本添加的自定义函数

javascript - jQuery 生成密码

javascript - 在自调用函数外获取变量和数组的值

C 全局函数(非 C++)

c - 是否可以在函数原型(prototype)中指定返回类型而不是在c中的函数定义中指定返回类型?

python - 在多个模块中使用函数类型的错误签名错误