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
Getting global Javascript variable in another Javascript file
提问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 myVariable
variable. 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
回答by redexp
Anything that you will put in window
in any place (even in functions) will be visible in global scope. So
您将放置在window
任何地方(甚至在函数中)的任何内容都将在全局范围内可见。所以
<script type="text/javascript">
window.myVariable = "something";
</script>
And myVariable
will 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 文件中的全局变量是在将在同一页面上使用它的脚本之前定义的,则您可以使用它。