2016-03-30 110 views
0

我一直在試圖理解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

等待!?他在問什麼?他想通過單擊右鍵來顯示它? http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_webstorage_local_clickcount – stanley1943

+0

奇怪的開始與0硬幣每次我刷新頁面:( – jmadp

回答

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

非常感謝你的這一點,這就是我一直在尋找的:) – jmadp

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

有了它,它甚至不增加更多。感謝您的回覆tho :) – jmadp

+0

用小提琴檢查修改後的答案 – Ash