我一直在努力理解localstorage
并遇到了一些问题。
当我添加以下代码时,我刷新网站的数字将为零,直到我按下按钮。但是当我刷新网站时,我想让它显示最新的数字。
function CollectCoin() {
if(typeof(Storage) !== "undefined") {
if (localStorage.clickcount) {
localStorage.clickcount = Number(localStorage.clickcount)+1;
} else {
localStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "Total coins: " + localStorage.clickcount;
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
}
}
我希望有人可以帮我解决这个问题并向我解释如何解决这个问题。
答案 0 :(得分:0)
请在此处查看:https://jsfiddle.net/nueffmvm/
function CollectCoin() {
if(localStorage) {
if(localStorage.clickCount == "NaN"){
localStorage.clickCount = 1;
}
else{
localStorage.clickCount++;
}
document.getElementById("result").innerHTML = "Total coins: " + localStorage.clickCount;
}
else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
}
}
答案 1 :(得分:0)
您希望它显示数字。这比简单的函数
更复杂https://jsfiddle.net/ed5unzf6/1/
HTML:
<div id="result">Total coins: 0</div>
<button id="coinButton">Collect Coins</button>
使用Javascript:
//Check if Local Storage is available
if (typeof(Storage) == 'undefined'){
document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
}else{
display(); //display the coin count
//when user click the button, it adds 1
document.getElementById('coinButton').addEventListener('click', addcoin);
}
function addcoin() {
localStorage.clickcount = Number(localStorage.clickcount)+1;
display();
}
//display function
function display() {
//Check if clickcount is available. Only Number is tested, so use isNaN
if (!localStorage.clickcount || isNaN(localStorage.clickcount)){
localStorage.clickcount = 0;
}
document.getElementById("result").innerHTML = "Total coins: " + Number(localStorage.clickcount);
}