简体   繁体   中英

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:

var glbValue;

and putting the value of global variable glbValue from first.html eg:

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

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

Try to use the local storage :

first.html :

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

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 .

  1. Use localStorage if you want the value to be preserverd even when you close the browswer.
  2. Use sessionStorage if you want the value to be preserved only during the current session.

I think that the 2º solution is the best in your case:

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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