刷新窗口后重置本地存储值

时间:2021-07-13 10:38:30

标签: javascript

我下面有一个代码

var amount = document.getElementById('downloads-t76a');

var current = 3700;
document.getElementById("downloads-t76a").innerHTML = localStorage.userTotal;

function update()
{
amount.innerText = format(current);
}

setInterval(function(){
current += Math.floor(Math.random() * 10);
localStorage.setItem('userTotal', current);
update();
},2000);

function format(amount)
{
var d = Math.floor(amount).toString().split('');
var c = (Math.round((amount%1)*100)/100).toString().split('.')[1];
if(typeof c == 'undefined'){
    c = '00';
}else if(c.length == 1){
    c = c + '0';
}
var str = '';
for(i=d.length-1; i>=0; i--){
    str += d.splice(0,1);
    if(i%3 == 0 && i != 0) str += ',';
}
return str;
}

基本上在用户第一次访问站点后,该值从 3700 开始,该值每 2 秒更新一次。问题是当我刷新窗口值时再次从 3700 开始,但我希望它是用户刷新之前的最后更新值。

1 个答案:

答案 0 :(得分:0)

当你刷新你的脚本时,新的开始。因此,无法访问先前代码中的任何内容。正是您使用 localStorage 的原因。

var storageValue = localStorage.getItem('userTotal') ;
var current = storageValue === null ? 3700 : (+JSON.parse(storageValue));

使用 + 运算符作为 getItem() 返回一个 DOMString。我们需要将其转换为数字。