简体   繁体   English

javascript中的全局变量(从一个文件中声明它,从另一个文件中放入值,然后从另一个文件中访问它)

[英]Global variable in javascript (declare it from one file, put value from another file and accessing it from some another file)

I declared javascript global variable in global.js file eg: 我在global.js文件中声明了javascript全局变量,例如:

var glbValue;

and putting the value of global variable glbValue from first.html eg: 并放置来自first.html的全局变量glbValue的值,例如:

<script type="text/javascript" src="global.js"></script>
<script type="text/javascript">
function onBtnSubmit()
{
   glbValue=123;
}
</script>

and accessing the global variable glbValue from second.html eg: 并从second.html访问全局变量glbValue,例如:

<script type="text/javascript" src="global.js"></script>
<script type="text/javascript">
function onBtnClick()
{
   alert(glbValue);
}
</script>

it gives me output undefined inplace of 123, why ? 它给我输出未定义的123,为什么?

Try to use the local storage : 尝试使用本地存储:

first.html : first.html

localStorage.setItem("glbValue", "123");

second.html : second.html

alert(localStorage.getItem("glbValue"));

When a page loads, all its script files are executed in a new context. 页面加载时,其所有脚本文件都在新的上下文中执行。 The browser does not ' remember ' what you did in the last page. 浏览器不会“ 记住 ”您在上一页中所做的操作。 If you want to share a variable between pages, either you use cookies or, even better, localStorage or sessionStorage . 如果要在页面之间共享变量,则可以使用Cookie,或者甚至可以使用localStoragesessionStorage

  1. Use localStorage if you want the value to be preserverd even when you close the browswer. 如果您希望即使在关闭浏览器时仍保留该值,请使用localStorage
  2. Use sessionStorage if you want the value to be preserved only during the current session. 如果希望仅在当前会话期间保留值,请使用sessionStorage

I think that the 2º solution is the best in your case: 我认为2º解决方案是您的最佳选择:

first.html : first.html

<script type="text/javascript">
function onBtnSubmit()
{
   sessionStorage.setItem('gblValue', 123);
}
</script>

second.html second.html

<script type="text/javascript">
function onBtnClick()
{
   alert(sessionStorage.getItem('gblValue'));
}
</script>

You no longer need that global variable. 您不再需要该全局变量。 The only problem with this solution is that IE8 and below do not support this, but there are good polyfills that use cookies transparently. 此解决方案的唯一问题是IE8及以下版本不支持此功能,但是有很好的polyfill可以透明地使用cookie。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM