如何让页面刷新后JS变量保留价值? [英] How to get JS variable to retain value after page refresh?
问题描述
是否可以永久更改JavaScript变量?就像在,如果我设置变量X并使其等于1.然后onClick按钮将该变量更改为2.我怎样才能让该变量在页面刷新时保持2?
window.localStorage
(或 window.sessionStorage
)。不同之处在于,只要浏览器保持打开状态, sessionStorage
就会持续存在, localStorage
在浏览器重新启动后仍然存在。持久性适用于整个网站不只是它的一个页面。 当你需要设置一个应该反映在下一页,使用:
var someVarName =value;
localStorage.setItem(someVarName,someVarName);
在任何页面中(例如页面加载时),都可以这样:
var someVarName = localStorage.getItem(someVarName);
.getItem()
将返回 null
如果没有存储值或存储的值。
请注意,只有字符串值可以存储在此存储中,但这可以通过使用 JSON.stringify
和 JSON.parse
来克服。从技术上讲,无论何时调用 .setItem()
,它都会调用 .toString()
并存储该值。
MDN的DOM存储指南(链接如下),有变通办法/ polyfills,最终回落到像cookies这样的东西,如果 localStorage
不可用。
使用现有的或创建您自己的迷你库并不是一个坏主意,它可以提取保存的能力任何数据类型(如对象文字,数组等)。
参考文献:
- 浏览器
存储
- https://developer.mozilla.org/zh-CN/docs/Web/Guide/API/DOM/Storage -
localStorage
- https://developer.mozilla.org/zh-CN/docs/DOM/Storage#localStorage -
JSON
- https://developer.mozilla .org / zh-CN / docs / JSON - 浏览器存储兼容性 - http://caniuse.com/namevalue-storage
- 存储对象 -
Is it possible to permanently change a javascript variable? As in, if I set the variable X and make that equal to 1. Then onClick of a button change that variable to 2. How can I get that variable to stay at 2 on refresh of the page?
This is possible with window.localStorage
(or window.sessionStorage
). The difference is that sessionStorage
lasts for as long as the browser stays open, localStorage
survives past browser restarts. The persistence applies to the entire web site not just a single page of it.
When you need to set a variable that should be reflected in the next page(s), use:
var someVarName = "value";
localStorage.setItem("someVarName", someVarName);
And in any page (like when the page has loaded), get it like:
var someVarName = localStorage.getItem("someVarName");
.getItem()
will return null
if no value stored, or the value stored.
Note that only string values can be stored in this storage, but this can be overcome by using JSON.stringify
and JSON.parse
. Technically, whenever you call .setItem()
, it will call .toString()
on the value and store that.
MDN's DOM storage guide (linked below), has workarounds/polyfills, that end up falling back to stuff like cookies, if localStorage
isn't available.
It wouldn't be a bad idea to use an existing, or create your own mini library, that abstracts the ability to save any data type (like object literals, arrays, etc.).
References:
- Browser
Storage
- https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage localStorage
- https://developer.mozilla.org/en-US/docs/DOM/Storage#localStorageJSON
- https://developer.mozilla.org/en-US/docs/JSON- Browser Storage compatibility - http://caniuse.com/namevalue-storage
- Storing objects - Storing Objects in HTML5 localStorage
这篇关于如何让页面刷新后JS变量保留价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!