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

时间:2017-08-14 09:17:56

标签: javascript jquery

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

<meta http-equiv="refresh" content="30">

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

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

2 个答案:

答案 0 :(得分:0)

首先检查您的浏览器是否支持这样的本地存储(本地存储将在页面刷新期间保持不同于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..
}

答案 1 :(得分:0)

假设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项目&#34; titles&#34;。

如果是这样,&#34;标题&#34;增加1,结果值分配给&#34; myId&#34;。

如果尚未使用localStorage项目,则使用起始值对其进行初始化,并将起始值分配给&#34; myId&#34;同样。

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

相关问题