jQuery 在另一个 Javascript 文件中获取全局 Javascript 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18482741/
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-26 21:43:57  来源:igfitidea点击:

Getting global Javascript variable in another Javascript file

javascriptjquery

提问by user2219247

Lets say I have a variable:

假设我有一个变量:

<script type="text/javascript">
    var myVariable = "something";
</script>

After this js global variable declaration I have another javascript:

在这个 js 全局变量声明之后,我有另一个 javascript:

<script type="text/javascript" src="myScriptFile.js"></script>

In this file I need to use the value of my global myVariablevariable. I know that I can do it by setting this value in some HTML, then using DOM or jQuery or something else get this value in the file, but I want to avoid creating those kind of hidden fields in my HTML. Is there any better way to do this?

在这个文件中,我需要使用我的全局myVariable变量的值。我知道我可以通过在一些 HTML 中设置这个值来做到这一点,然后使用 DOM 或 jQuery 或其他东西在文件中获取这个值,但我想避免在我的 HTML 中创建那些类型的隐藏字段。有没有更好的方法来做到这一点?

回答by Tushar Gupta - curioustushar

Make it global;

使其成为全球性的

script1.js

脚本1.js

 var foobar = "O HAI";

script2.js

脚本2.js

  alert(foobar);

回答by redexp

Anything that you will put in windowin any place (even in functions) will be visible in global scope. So

您将放置在window任何地方(甚至在函数中)的任何内容都将在全局范围内可见。所以

<script type="text/javascript">
    window.myVariable = "something";
</script>

And myVariablewill be visible anywhere

并且myVariable随处可见

回答by Víctor Due?as Robles

I use global variables with

我使用全局变量

jQuery.data(document.body, "varAgrup", { var1: value1, var2: value2 });

I get var value with

我得到 var 值

jQuery.data(document.body, "varAgrup").var1;

回答by Alexandr Mihalciuc

You can use the global variable in the myScriptFile.js file if it was defined before the script which will use it on the same page.

如果 myScriptFile.js 文件中的全局变量是在将在同一页面上使用它的脚本之前定义的,则您可以使用它。