简体   繁体   English

在页面之间同步 JavaScript 变量

[英]Sync a JavaScript variable between pages

I have been looking for ages trying to find a way to access a variable in another.html file.我一直在寻找一种方法来访问 another.html 文件中的变量。 For example: File 1 (HTML)例如:文件 1 (HTML)

<!--some code-->
<script>
var x; //this should equal the variable in the other file.
</script>

File 2 (HTML)文件 2 (HTML)

<!--some code-->
<script>
var y = 0;
</script>

How could I do it?我怎么能做到? (I can move file 2's code into a separate.js file. (我可以将文件 2 的代码移动到一个单独的 .js 文件中。

You'll have better luck storing the variable in localStorage.将变量存储在 localStorage 中会更好。

Set the key in one page一页设置key

localStorage.setItem('key', value);

Retrieve the value from another从另一个检索值

localStorage.getItem('key')

The other way is to use cookies .另一种方法是使用cookies

For this you can use localStorage which is supported in all modern browsers.为此,您可以使用所有现代浏览器都支持的localStorage

Note that localStorage.setItem() will do .toString() on everything that you attempt to store that isn't a string yet.请注意, localStorage.setItem()将对您尝试存储的还不是字符串的所有内容执行.toString() It is best to use JSON.stringify() and JSON.parse() for setting and retrieving everything.最好使用JSON.stringify()JSON.parse()来设置和检索所有内容。 Doing so may not be needed for strings themselves but it doesn't hurt much to just do it always.字符串本身可能不需要这样做,但总是这样做并没有太大的伤害。

I often use helper functions to make working with it easier, like this:我经常使用辅助函数来使其更容易使用,如下所示:

function storeObject(key, x) {
  localStorage.setItem(key, JSON.stringify(x));
}

function retrieveObject(key) {
  return JSON.parse(localStorage.getItem(key));
}

storeObject("test", { a: 2, b: 3 } );

const obj = retrieveObject("test")
console.dir(obj.a); // prints 2
console.dir(obj.b); // prints 3

PS I did not create a Stack Snippet because snippets don't allow the use of localStorage. PS 我没有创建堆栈片段,因为片段不允许使用 localStorage。

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

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