2017-08-10 25 views
-2

我希望我的頁面能夠執行以下操作: 當用戶進入頁面時有「貨幣」值,並且有東西要購買。當用戶點擊購買東西時,它從15美元(我已經編寫了這個腳本)中扣除,但是當你刷新頁面時,它重置爲15美元。在html中使用本地存儲的貨幣系統

我該如何讓它保持它的價值取決於用戶刷新後花費了多少,以便我可以編輯html以再次放置任何價值的貨幣?我嘗試了localstorage,但我似乎沒有得到它的工作。

var money= 15; 
if (money >= 2) { 
    snd.play(); 
    //the first statement should generate a random number in the range 0 to 6 (the subscript values of the image file names in the imagesArray) 
    var num = Math.floor(Math.random() * 21); // 0...6 
    //the second statement display the random image from the imagesArray array in the canvas image using the random number as the subscript value 
    document.canvas.src = imagesArray[num]; 
    money=money-2; 
    document.getElementById("wallet").innerHTML = money; 
    alert.style.display = "block"; 

    span.onclick = function() { 
    alert.style.display = "none"; 
    } 

    window.onclick = function(event) { 
    if (event.target == alert) { 
     alert.style.display = "none"; 
    } 
    } 
} else { 
    alert("Payment was not recieved: Insufficient funds."); 
} 
} 

這就是我想要的工作就像我所描述的功能,但具有本地存儲,而不是僅僅money=money-2

+0

我已經重新格式化了你的代碼 - 但有一個未修改的'}' – symcbean

+2

「我試過localstorage,但我似乎沒有得到它的工作」 - 不在你在這裏顯示的代碼。 – symcbean

+0

感謝嘗試人,我的代碼總是亂七八糟 –

回答

0

如果你真的想使用LocalStorage這真的是quite simple to do

要設置值:

localStorage.setItem('myCat', 'Tom'); 

要獲得該值:

localStorage.getItem('myCat'); 

所以,你可以在你的頁面加載做的是從本地存儲得到的錢,使用,如果它如果它不刺激,爲本地存儲節省一個新的「開始」價值。