javascript - 在 js 文件之外调用 JavaScript 函数

标签 javascript html


我在从其他 HTML 页面调用 JavaScript 函数(位于对象内部,在它自己的 .js 文件中)时遇到问题。在代码示例中,我将仅使用一个简单的 Hello World 函数。

    //.js file

    window.addEvent('domready',function(){

      var Site = {
        //Here I have like three other functions

        //This function I want to detect the browser version. I use MooTools for this
        detectBrowser : function(){
         if(Browser.ie){
          //Then what ever content goes here
         }
        } 
       }

       //I execute the other three functions here because they need to be called on every page
       Site.dropdownmenu();
       Site.accordion();
       Site.lightbox();
     });

我正在使用 MooTools,因此我已将所有内容包装在 domready 函数中。
现在,我希望这个 cetect 函数在一页上执行。我尝试过这样的想法:

    //In the HTML file between two script tags:
    Site.alert(); 

那是行不通的。有什么想法吗?
如果我在 .js 文件中执行它,它就可以正常工作。但我不希望它在每个页面都执行。

最佳答案

如果在函数中使用 var 声明变量,则该变量是该函数的本地变量,并且无法从该函数外部访问。要使其显式全局化,请将其声明为 window 的属性:

window.addEvent('domready',function(){
    window.Site = ...

这对于代码的工作来说并不是必需的,它只是让可能读取您代码的程序员明确知道 Site 是全局的。

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

相关文章:

javascript - 直接在追加中添加属性

javascript - 如何在多个相同元素类中具有特定类的第一个和最后一个元素添加类?

javascript - 比较 JavaScript 中的函数参数

javascript - 我想使用 jQuery 在 html 中使用 data-* 属性将占位符设置为文本框?

javascript - 修复了 .js 页面堆积脚本顶部的导航栏

javascript - 使用 jQuery 随机显示/隐藏图像

Javascript - 重复字符

javascript - 如何在 spring 中使用 ajax jQuery

jquery - 阅读更多动画/过渡

javascript - 发射器跟随 Canvas 中的粒子