Html 页面刷新后如何让JS变量保留值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16206322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 07:51:22  来源:igfitidea点击:

How to get JS variable to retain value after page refresh?

javascripthtml

提问by Josh Woelfel

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?

是否可以永久更改 javascript 变量?如,如果我设置变量 X 并使其等于 1。然后单击按钮将该变量更改为 2。如何在刷新页面时使该变量保持在 2?

回答by Ian

This is possible with window.localStorageor window.sessionStorage. The difference is that sessionStoragelasts for as long as the browser stays open, localStoragesurvives past browser restarts. The persistence applies to the entire web sitenot just a single page of it.

这可以使用window.localStoragewindow.sessionStorage。不同之处在于sessionStorage,只要浏览器保持打开状态,它就会持续存在,并在浏览localStorage器重新启动后继续存在。持久性适用于整个网站,而不仅仅是它的一个页面。

When you need to set a variable that should be reflected in the next page(s), use:

当您需要设置应反映在下一页中的变量时,请使用:

var someVarName = "value";
localStorage.setItem("someVarKey", someVarName);

And in any page (like when the page has loaded), get it like:

在任何页面中(比如页面加载后),得到它:

var someVarName = localStorage.getItem("someVarKey");

.getItem()will return nullif no value stored, or the value stored.

.getItem()null如果没有存储值或存储的值,将返回。

Note that only string valuescan be stored in this storage, but this can be overcome by using JSON.stringifyand JSON.parse. Technically, whenever you call .setItem(), it will call .toString()on the value and store that.

请注意,此存储中只能存储字符串值,但这可以通过使用JSON.stringify和来克服JSON.parse。从技术上讲,无论何时您调用.setItem(),它都会调用.toString()该值并存储该值。

MDN's DOM storage guide (linked below), has workarounds/polyfills, that end up falling back to stuff like cookies, if localStorageisn't available.

MDN 的 DOM 存储指南(链接如下),有解决方法/polyfills,如果localStorage不可用,最终会退回到 cookie 之类的东西。

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:

参考:

回答by Dagg Nabbit

In addition to cookies and localStorage, there's at least one other place you can store "semi-persistent" client data: window.name. Any string value you assign to window.namewill stay there until the window is closed.

除了 cookie 和 之外localStorage,至少还有一个其他地方可以存储“半持久”客户端数据:window.name. 您分配给的任何字符串值都window.name将保留在那里,直到窗口关闭。

To test it out, just open the console and type window.name = "foo", then refresh the page and type window.name; it should respond with foo.

要测试它,只需打开控制台并键入window.name = "foo",然后刷新页面并键入window.name; 它应该以foo.

This is a bit of a hack, but if you don't want cookies filled with unnecessary data being sent to the server with every request, and if you can't use localStoragefor whatever reason (legacy clients), it may be an option to consider.

这有点麻烦,但是如果您不希望每次请求都将充满不必要数据的 cookie 发送到服务器,并且localStorage由于某种原因(旧客户端)而无法使用,则可以选择考虑。

window.namehas another interesting property: it's visible to windows served from other domains; it's not subject to the same-origin policy like nearly every other property of window. So, in addition to storing "semi-persistent" data there while the user navigates or refreshes the page, you can also use it for CORS-free cross-domain communication.

window.name还有一个有趣的特性:它对来自其他域的窗口可见;它不像window. 因此,除了在用户导航或刷新页面时将“半持久”数据存储在那里之外,您还可以将其用于无 CORS 的跨域通信。

Note that window.namecan only store strings, but with the wide availability of JSON, this shouldn't be much of an issue even for complex data.

请注意,window.name只能存储字符串,但由于 的广泛可用性JSON,即使对于复杂数据,这也不是什么大问题。

回答by Arun P Johny

You will have to use cookie to store the value across page refresh. You can use any one of the many javascript based cookie libraries to simplify the cookie access, like this one

您将不得不使用 cookie 来存储跨页面刷新的值。您可以使用许多基于 javascript 的 cookie 库中的任何一种来简化 cookie 访问,就像这个

If you want to support only html5 then you can think of Storageapi like localStorage/sessionStorage

如果您只想支持 html5,那么您可以将Storageapi视为 localStorage/ sessionStorage

Ex: using localStorageand cookies library

例如:使用localStoragecookie 库

var mode = getStoredValue('myPageMode');

function buttonClick(mode) {
    mode = mode;
    storeValue('myPageMode', mode);
}

function storeValue(key, value) {
    if (localStorage) {
        localStorage.setItem(key, value);
    } else {
        $.cookies.set(key, value);
    }
}

function getStoredValue(key) {
    if (localStorage) {
        return localStorage.getItem(key);
    } else {
        return $.cookies.get(key);
    }
}

回答by hieu.do

You can do that by storing cookies on client side.

您可以通过在客户端存储 cookie 来做到这一点。