在html中使用localstorage的money系统

时间:2017-08-10 11:48:06

标签: javascript

我希望我的网页能够执行以下操作: 当用户进入页面时存在“钱”值,并且有需要购买的东西。当用户点击购买东西时,它会从15美元中扣除(我已经编写了这个脚本),但是当你刷新页面时它会重置为15美元。

我如何保持它的价值取决于用户在刷新后花了多少钱,以便我可以编辑html以再次提供任何价值?我试过本地存储,但我似乎没有让它工作。

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

1 个答案:

答案 0 :(得分:0)

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

设置值:

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

获得该值:

localStorage.getItem('myCat');

因此,您在页面加载上可以做的就是从本地存储中获取资金,如果它存在则使用它,如果它不存在则保存新的'价值到本地存储。

相关问题