Javascript Javascript中跨多个文件的全局变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2932782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:33:31  来源:igfitidea点击:

Global variables in Javascript across multiple files

javascriptscopeglobal-variablesglobal

提问by Goro

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.

我的一些 JavaScript 代码位于名为 helpers.js 的外部文件中。在调用此 JavaScript 代码的 HTML 中,我发现自己需要知道 helpers.js 中的某个函数是否已被调用。

I have attempted to create a global variable by defining:

我试图通过定义来创建一个全局变量:

var myFunctionTag = true;

In global scope both in my HTML code and in helpers.js.

在我的 HTML 代码和 helpers.js 中的全局范围内。

Heres what my html code looks like:

这是我的 html 代码的样子:

<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?

我正在尝试做的甚至可行吗?

采纳答案by tvanfosson

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.

您需要在包含 helpers.js 文件之前声明该变量。只需在 helpers.js 的包含上方创建一个脚本标记并在那里定义它。

<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>

回答by Stephen P

The variable can be declared in the .jsfile and simply referenced in the HTML file. My version of helpers.js:

该变量可以在.js文件中声明并在 HTML 文件中简单地引用。我的版本helpers.js

var myFunctionWasCalled = false;

function doFoo()
{
    if (!myFunctionWasCalled) {
        alert("doFoo called for the very first time!");
        myFunctionWasCalled = true;
    }
    else {
        alert("doFoo called again");
    }
}

And a page to test it:

还有一个页面来测试它:

<html>
<head>
<title>Test Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<script type="text/javascript" src="helpers.js"></script>
</head>

<body>


<p>myFunctionWasCalled is
<script type="text/javascript">document.write(myFunctionWasCalled);</script>
</p>

<script type="text/javascript">doFoo();</script>

<p>Some stuff in between</p>

<script type="text/javascript">doFoo();</script>

<p>myFunctionWasCalled is
<script type="text/javascript">document.write(myFunctionWasCalled);</script>
</p>

</body>
</html>

You'll see the test alert()will display two different things, and the value written to the page will be different the second time.

您将看到测试alert()将显示两种不同的内容,并且第二次写入页面的值将有所不同。

回答by Martin

OK, guys, here's my little test too. I had a similar problem, so I decided to test out 3 situations:

好的,伙计们,这也是我的小测试。我遇到了类似的问题,所以我决定测试 3 种情况:

  1. One HTML file, one external JS file... does it work at all - can functions communicate via a global var?
  2. Two HTML files, one external JS file, one browser, two tabs: will they interfere via the global var?
  3. One HTML file, open by 2 browsers, will it work and will they interfere?
  1. 一个 HTML 文件,一个外部 JS 文件......它真的有效吗 - 函数可以通过全局变量进行通信吗?
  2. 两个 HTML 文件、一个外部 JS 文件、一个浏览器、两个选项卡:它们会通过全局变量进行干扰吗?
  3. 一个 HTML 文件,由 2 个浏览器打开,它会起作用吗?它们会干扰吗?

All the results were as expected.

所有的结果都符合预期。

  1. It works. Functions f1() and f2() communicate via global var (var is in the external JS file, not in HTML file).
  2. They do not interfere. Apparently distinct copies of JS file have been made for each browser tab, each HTML page.
  3. All works independently, as expected.
  1. 有用。函数 f1() 和 f2() 通过全局 var 进行通信(var 在外部 JS 文件中,而不是在 HTML 文件中)。
  2. 他们不干涉。显然,每个浏览器选项卡、每个 HTML 页面都制作了不同的 JS 文件副本。
  3. 正如预期的那样,所有这些都独立工作。

Instead of browsing tutorials, I found it easier to try it out, so I did. My conclusion: whenever you include an external JS file in your HTML page, the contents of the external JS gets "copy/pasted" into your HTML page before the page is rendered. Or into your PHP page if you will. Please correct me if I'm wrong here.Thanx.

我发现尝试使用它更容易,而不是浏览教程,所以我这样做了。我的结论是:每当您在 HTML 页面中包含外部 JS 文件时,外部 JS 的内容都会在页面呈现之前“复制/粘贴”到您的 HTML 页面中。或者,如果您愿意,也可以进入您的 PHP 页面。如果我在这里错了,请纠正我。谢谢。

My example files follow:

我的示例文件如下:

EXTERNAL JS:

外部JS:

var global = 0;

function f1()
{
    alert('fired: f1');
    global = 1;
    alert('global changed to 1');
}

function f2()
{
    alert('fired f2');
    alert('value of global: '+global);
}

HTML 1:

HTML 1:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="external.js"></script>
<title>External JS Globals - index.php</title>
</head>
<body>
<button type="button" id="button1" onclick="f1();"> fire f1 </button>
<br />
<button type="button" id="button2" onclick="f2();"> fire f2 </button>
<br />
</body>
</html>

HTML 2

HTML 2

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="external.js"></script>
<title>External JS Globals - index2.php</title>
</head>
<body>
<button type="button" id="button1" onclick="f1();"> fire f1 </button>
<br />
<button type="button" id="button2" onclick="f2();"> fire f2 </button>
<br />
</body>
</html>

回答by paulo62

I think you should be using "local storage" rather than global variables.

我认为您应该使用“本地存储”而不是全局变量。

If you are concerned that "local storage" may not be supported in very old browsers, consider using an existing plug-in which checks the availability of "local storage" and uses other methods if it isn't available.

如果您担心非常旧的浏览器可能不支持“本地存储”,请考虑使用现有插件来检查“本地存储”的可用性,如果不可用,则使用其他方法。

I used http://www.jstorage.info/and I'm happy with it so far.

我使用了 http://www.jstorage.info/,到目前为止我很满意。

回答by partizanos

You can make a json object like:

您可以创建一个 json 对象,例如:

globalVariable={example_attribute:"SomeValue"}; 

in fileA.js

在文件 A.js 中

And access it from fileB.js like: globalVariable.example_attribute

并从 fileB.js 访问它,例如: globalVariable.example_attribute

回答by Sajith

Hi to pass values from one js file to another js file we can use Local storage concept

嗨,将值从一个 js 文件传递​​到另一个 js 文件,我们可以使用本地存储概念

<body>
<script src="two.js"></script>
<script src="three.js"></script>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
</body>

Two.js file

二.js文件

function myFunction() {
var test =localStorage.name;

 alert(test);
}

Three.js File

三.js文件

localStorage.name = 1;

回答by MrJ

//Javascript file 1

//Javascript文件1

localStorage.setItem('Data',10);

//Javascript file 2

//Javascript文件2

var number=localStorage.getItem('Data');

Don't forget to link your JS files in html :)

不要忘记在 html 中链接您的 JS 文件:)