简体   繁体   English

无法在另一个js文件中获取全局变量

[英]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.

相关问题 在cakephp中如何创建另一个文件,例如core.php文件,并在js文件中调用全局变量 - in cakephp how to create another file like core.php file and call global variable in js file 使用webpack无法从主JS文件中的其他JS文件获取全局变量 - Can't get global variable from other JS file in main JS file with webpack 如何将全局变量值从js文件中的函数传递到其他文件中的另一个函数 - How to pass a global variable value from a function in a js file to another function in a different file 在 Javascript 我无法获取要更新的全局变量 - in Javascript I cannot get a global variable to update 如何将新元素推送到另一个.js文件中的JavaScript全局变量中创建的数组? - How to push new element to an array created in JavaScript global variable in another .js file? Javascript:从另一个js文件访问全局变量时,其值会丢失 - Javascript: Global variable loses its value when accessed from another js file 如何通过onclick函数设置全局变量并将其传递给另一个JS文件 - how to set global variable from onclick function and pass it to another JS file 如何将全局变量存储在一个 ajax 文件中并从另一个 ajax 文件中获取? - How to store global variable in one ajax file and get from another ajax file? 如何将全局变量导入另一个文件? - How can import a global variable into another file? 无法访问另一个文件中的全局变量 - Global variable in another file can't be accessed
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM