[英]Cannot get global variable in another js file
I currently have this global variable declared in javascript.js which I've imported to my main document. 我目前在javascript.js中声明了此全局变量,并将其导入到主文档中。
var globalURL = "test URL";
When I try an alert within the javascript.js file it successfully outputs the value of globalURL. 当我在javascript.js文件中尝试警报时,它会成功输出globalURL的值。
However when I try to an alert with my current document but calling globalURL I get an error 但是,当我尝试使用当前文档发出警报但调用globalURL时,出现错误
Uncaught ReferenceError: globalURL is not defined
I'm I doing something wrong here? 我在这里做错了吗? I followed the example here but still it doesn't work for me.
我在这里按照示例进行操作,但仍然对我不起作用。 Can I access variables from another file?
我可以从另一个文件访问变量吗?
UPDATE: I have included my javascript.js file with my current document, so I don't think the error is there. 更新:我已经将javascript.js文件包含在当前文档中,所以我不认为该错误存在。 Otherwise the first alert function within the javascript.js wouldn't have run at all.
否则,javascript.js中的第一个警报功能将根本无法运行。
在HTML文件中,您可能先加载使用globalURL的文件,然后再加载设置globalURL的文件。
Open your browser's developer section and there scripts tabs. 打开浏览器的开发人员部分,然后单击脚本选项卡。 Observe that both js files are loaded into memory.
观察两个js文件都已加载到内存中。 I believe one of them is not loaded.
我相信其中一个未加载。 Global valiarbles in js are available in combined space.
js中的全局变量可在组合空间中使用。
Another possibility is that you might be declaring it from inside of a function somewhere. 另一种可能性是您可能是在某个函数的内部声明它的。 If you want to declare a global variable from inside a function, try leaving off the
var
at the beginning. 如果要从函数内部声明全局变量,请尝试在开始时
var
。 This would look like globalURL = "test URL";
看起来像
globalURL = "test URL";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.