如何让页面刷新后JS变量保留价值? [英] How to get JS variable to retain value after page refresh?

查看:433
本文介绍了如何让页面刷新后JS变量保留价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以永久更改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 不可用。



使用现有的或创建您自己的迷你库并不是一个坏主意,它可以提取保存的能力任何数据类型(如对象文字,数组等)。






参考文献:




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:

这篇关于如何让页面刷新后JS变量保留价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆