2016-03-30 18 views
0

私はlocalstorageを理解しようとしており、少し問題が発生しました。 次のコードを追加すると、ボタンを押すまで番号がゼロになります。しかし、私はサイトをリフレッシュしたときに最新の番号を表示したい。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

Strangeは毎回私がページをリフレッシュするたびに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

これでさらに増えません。返信ありがとう: – jmadp

+0

修正された答えをフィドルで確認してください – Ash