2017-08-10 88 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'); 

所以,你可以在你的页面加载做的是从本地存储得到的钱,使用,如果它如果它不刺激,为本地存储节省一个新的“开始”价值。