【问题标题】:Localstorage little help neededLocalstorage 需要一点帮助
【发布时间】:2016-04-01 01:44:45
【问题描述】:

我一直在尝试理解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...";
    }
}

我希望有人可以帮助我解决这个问题并向我解释如何解决这个问题。

【问题讨论】:

  • 你的功能对我有用。
  • 等等!?他在问什么?他不想通过单击按钮来显示它吗? w3schools.com/html/…
  • 每次刷新页面时奇怪的开始都是0个硬币:(
  • @Stanley1943 那是我得到代码的地方!但我希望这个数字随着按钮的增加而增加,但也希望它在我刷新我离开的地方时显示出来,这样人们就不会感到困惑了。
  • 您的代码对我有用。你确定你没有在另一段代码中重置localStorage.clickcount 的值吗?

标签: javascript html local-storage


【解决方案1】:

您希望它显示数字。这比简单的功能更复杂

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);
}

【讨论】:

  • 非常感谢你,这就是我要找的:)
【解决方案2】:

请在此处查看它的工作原理: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...";
    }
}

【讨论】:

  • 有了这个,它甚至不会增加更多。感谢您的回复:)
  • 用小提琴检查修改后的答案
猜你喜欢
  • 2012-03-21
  • 2018-05-21
  • 2014-09-22
  • 2014-04-07
  • 1970-01-01
  • 2020-05-29
  • 2016-09-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多