-2

您可以在此应用 localStorage 吗?如果我点击“Deduct”,id“slot”将减少为1。我想学习的是如何应用localStorage。如果 slot 是 9,如果我刷新/关闭浏览器或重新启动计算机并再次运行程序,则 slot 将保持 9。我很难学习 localStorage,需要帮助大师。

<script>
var availableSlot1 = 10;
var reduceSlot1 = function(valueToDeduct1){
    availableSlot1 = availableSlot1 - valueToDeduct1;
    document.getElementById('slot').innerHTML = availableSlot1;
    var x = storage.key(availableSlot1);
    if (availableSlot1 == 0){
        document.getElementById('x').innerHTML = "FULL";
        document.getElementById("button1").style.display = "none";
    }
};
</script>

<p id="slot">10</p>
<a href="javascript:reduceSlot1(1)" id="button1">Deduct</a>

EDITED:
<script>
var slot = localStorage.getItem("slot");
if (typeof slot == "undefined") {
     slot = 10;
}
document.getElementById("slot").innerHTML = slot;

var reduceSlot1 = function reduceSlot(by) 
 {
  if (slot >= by) {
      slot -= by;
      document.getElementById("slot").innerHTML = slot;
       localStorage.setItem("slot", slot);
 } 
else {
      document.getElementById('slot').innerHTML = "FULL";
      document.getElementById("button1").style.display = "none";
    }
 }
</script>

我遵循了代码,但是它不起作用。

4

2 回答 2

1

本地存储现场演示

您可以使用localStorage.name, 代替 name 使用本地存储,您可以使用任何属性。

var i = 1;
localStorage.name = i;
于 2013-10-02T09:50:54.117 回答
0

http://jsfiddle.net/flocsy/mrhwK/

var slot = localStorage.getItem("slot");
if (slot == null) {
  slot = 10;
}
document.getElementById("slot").innerText = slot;

function reduceSlot() {
    if (slot >= 1) {
        slot --;
        document.getElementById("slot").innerText = slot;
        localStorage.setItem("slot", slot);
    } else {
        document.getElementById('x').innerText = "FULL";
        document.getElementById("button1").style.display = "none";
    }
}

document.getElementById("button1").onclick = reduceSlot;
于 2013-10-02T09:46:26.953 回答