繁体   English   中英

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

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

我在global.js文件中声明了javascript全局变量,例如:

var glbValue;

并放置来自first.html的全局变量glbValue的值,例如:

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

并从second.html访问全局变量glbValue,例如:

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

它给我输出未定义的123,为什么?

尝试使用本地存储:

first.html

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

second.html

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

页面加载时,其所有脚本文件都在新的上下文中执行。 浏览器不会“ 记住 ”您在上一页中所做的操作。 如果要在页面之间共享变量,则可以使用Cookie,或者甚至可以使用localStoragesessionStorage

  1. 如果您希望即使在关闭浏览器时仍保留该值,请使用localStorage
  2. 如果希望仅在当前会话期间保留值,请使用sessionStorage

我认为2º解决方案是您的最佳选择:

first.html

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

second.html

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

您不再需要该全局变量。 此解决方案的唯一问题是IE8及以下版本不支持此功能,但是有很好的polyfill可以透明地使用cookie。

暂无
暂无

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

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