2017-04-25 43 views
0

由於標題可能會放棄,我正試圖跨頁刷新增加分數值。我不完全確定我的設置是否正確,因此有點評論。不尋找直接的答案,只是一些指針和建議,以達到我需要的地方。在jquery中增加和存儲變種

var score = 0; 
//localStorage.setItem("score", score); 
var rounds; 
var ans; 
var img; 
img = document.getElementsByClassName("image")[0].id; 
$(".answer").click(function() { 
ans = $(this).attr('id'); 
if (ans === img) { 
    //score++; 
    //score = localStorage.getItem("score", score); 
    score++; 
    //localStorage.setItem("score", score); 
    //rounds++; 
    alert('right answer'); 
    location.reload(); 
} else { 
    //score = 0; 
    //rounds++; 
    alert('wrong answer'); 
    //location.reload(); 
} 
}); 
//var res = localStorage.getItem("score", score) 
//console.log(res); 

一直在玩查詢幾天,所以仍然盲目地感覺。任何幫助都會很棒。其餘的腳本可以在這裏找到jfiddle

+1

要堅持這一點對頁面刷新,你既可以將代碼存儲在後端,並在以後的時間把它或將它儲存在瀏覽器中(即餅乾)。我推薦後者。 – henry

+1

如果你想跨頁面加載而不使用數據庫/寫入文件來存儲一個值,你將需要了解創建/讀取cookies –

+2

正如@harrison所說,你需要將它存儲在某個地方,因爲JS中的變量無法在頁面中生存刷新。你的'localStorage'代碼有一些代碼。那有什麼問題? –

回答

2

我覺得你是在正確的軌道上使用localStorage。這很容易掌握,並且您已經開始實施一些代碼。你想要做的第一件事是通過調用localStorage.getItem('score');初始化分數變量。 getItem沒有第二個參數。

那麼你需要決定應該在增加之前還是之後保存分數?根據這個問題的答案,你會打電話localStorage.setItem('score', score);

https://developer.mozilla.org/en-US/docs/Web/API/Storage