我在从其他 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/