如何在页面重新加载时使用localStorage存储数字



嗨,我想存储一个值为0的数字

var count = 3; 
var count2 = "0"; 
var count3; 
var btn = document.getElementById("btn"); 

btn.onclick = function() {
count--; 
btn.style.transform = "scale(2)";
setTimeout(function() {
btn.style.transform = "scale(1)";
}, 0005); 
if(count === 0) {
/* I want to store the result here in manner that even when  the page  reload the number remains the same ( 0 in that case ) */ 

var zero = localStorage.getItem(count); 
count3 = parseInt(count2); 
localStorage.setItem( count , count3 ); 


}

}
#btn {
width : 300px;
height : 300px;
border : solid 2px red;
border-radius : 50%; 
transition : .1s;
}
<button id="btn">Click me</button>

但是我不需要影响count3来计数,因为count已经设置为0了:(但是我不能影响数字?我认为只有字符串在'key' localStorage。

我怎么能做到呢?

localstorage的关键是只使用String。您可以定义一个函数来解析任何....的键当页面重新加载时,localstorage不能被清除。所以你可以在你定义的函数中像var key = parse(localStorage.getitem(count))那样做。

localStorage。settitem (count, count3)

这是错误的。你应该写

localStorage。setItem("where", value);

因此,不应该将键中的项设置为变量count,而应该设置键"count"中的值,这是一个字符串。否则,每次更改整数count时,都将新值(count3)存储在一个新的位置。

当您重新加载页面时,整数count将尝试获取键3中的存储信息。


另外,count === 0也可以写成count == 0,这样它就不会先检查count是否为整数,而是接受字符串(布尔值,未定义和null)。


编辑:添加片段作为示例。我重构了代码,使其更具可读性,注释掉了localStorage,以便您可以在Stack Overflow上运行代码片段,并且我假设count不能低于0。

作为奖励,我删除了count2count3,同时将setTimeout从0.005 (5ms是最小的)更改为50ms (0.1s的一半是在过渡中)。

var storedCount = getStoredCount();
const GOT_PREVIOUS_VALUE = storedCount != null;
var count = (GOT_PREVIOUS_VALUE) ? storedCount : 3;
var btn = document.getElementById("btn");
btn.onclick = changeCount;
function changeCount() {
if (count > 0) {
count--;
scaleButton();
storeCount();
console.log({count})
}
}
function scaleButton() {
btn.style.transform = "scale(2)";
setTimeout(function() {
btn.style.transform = "scale(1)";
}, 50);
}
function getStoredCount() {
return localStorage.getItem('count') ;
}
function storeCount() {
localStorage.setItem('count', count);
}
#btn {
width: 300px;
height: 300px;
border: solid 2px red;
border-radius: 50%;
transition: .1s;
}
<button id="btn">Click me</button>

最新更新