Javascript中跨多个文件的全局变量 [英] Global variables in Javascript across multiple files
问题描述
我的一些 JavaScript 代码位于名为 helpers.js 的外部文件中.在调用此 JavaScript 代码的 HTML 中,我发现自己需要知道 helpers.js 中的某个函数是否已被调用.
A bunch of my JavaScript code is in an external file called helpers.js. Inside the HTML that calls this JavaScript code I find myself in need of knowing if a certain function from helpers.js has been called.
我试图通过定义来创建一个全局变量:
I have attempted to create a global variable by defining:
var myFunctionTag = true;
在我的 HTML 代码和 helpers.js 中的全局范围内.
In global scope both in my HTML code and in helpers.js.
我的 html 代码如下所示:
Heres what my html code looks like:
<html>
...
<script type='text/javascript' src='js/helpers.js'></script>
...
<script>
var myFunctionTag = false;
...
//I try to use myFunctionTag here but it is always false, even though it has been se t to 'true' in helpers.js
</script>
我正在尝试做的甚至可行吗?
Is what I am trying to do even feasible?
推荐答案
您需要在包含 helpers.js 文件之前声明该变量.只需在 helpers.js 的包含上方创建一个脚本标记并在那里定义它.
You need to declare the variable before you include the helpers.js file. Simply create a script tag above the include for helpers.js and define it there.
<script type='text/javascript' >
var myFunctionTag = false;
</script>
<script type='text/javascript' src='js/helpers.js'></script>
...
<script type='text/javascript' >
// rest of your code, which may depend on helpers.js
</script>
这篇关于Javascript中跨多个文件的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!