如何在本地存储中存储变量?

我正在运行一个脚本,我正在使用meta refresh因为它可能因互联网连接或服务器停机或任何事情而停止:

  

该脚本需要一个起始变量,每次脚本运行时都会更新,所以我想在本地存储中保存该变量的最新值,但是通过这种方式,该值将始终被覆盖到起始值

 var myId = 47911111; localStorage.setItem('titles', myId); 

首先检查您的浏览器是否支持这样的本地存储( 与sessionStorage不同,本地存储将在页面刷新期间保持不变

 if (typeof(Storage) !== "undefined") { // Code for localStorage/sessionStorage. // Store value localStorage.setItem("keyName", variable); // Retrieve value from local storage and assign to variable var myId = localStorage.getItem("keyName"); } else { // Sorry! No Web Storage support.. } 

假设localStorage可用,我理解你的问题:

 // first declare a variable but don't assign a value var myId; // then check whether your localStorage item already exists ... if (localStorage.getItem('titles')) { // if so, increase the value and assign it to your variable myId = parseInt(localStorage.getItem('titles')) + 1; // and reset the localStorage item with the new value localStorage.setItem('titles', myId); } else { // if localStorage item does not exist yet initialize // it with your strat value localStorage.setItem('titles', 1); // and assign start value to your variable myId = paresInt(localStorage.getItem('titles')); } console.log(myId); 

现在,每次页面加载代码时,都会检查是否存在localStorage项目“titles”。

如果是这样,“标题”的值增加1,结果值分配给“myId”。

如果localStorage项目尚未存在,则使用起始值进行初始化,并将起始值也分配给“myId”。

请注意,localStorage键和值始终是字符串,并且整数值始终转换为字符串。