2017-08-14 120 views
0

我运行一个脚本,我使用的是meta refresh,因为它可以阻止由于互联网连接或服务器停机时间或任何东西:如何将变量存储在本地存储中?

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

脚本需要开始变量,这将更新每个脚本运行时,所以我想保存在本地存储变量的最新值,但通过把它这样,该值将始终被覆盖到初始值

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

您已经在使用'localStorage.setItem()',那么问题 –

+0

还有什么问题,在页面刷新时不会被覆盖吗?我的意思是'myId'不会回到'47911111'? @JijoCleetus –

+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.. 
} 
+0

正如我在问题中所述,当页面刷新时不会被覆盖?我的意思是'myId'不会回到'47911111'? –

+0

您需要使用localStorage – Winnie

+0

将值重新分配给myID变量对不起,您是否可以在您的答案中详细说明该评论,并根据该答案反映该ID? –

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的项目“冠军”。

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

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

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

+0

解决了这个问题,但那也不错 –