My localStorage.clear(); won't work

My localStorage.clear(); won't work

本文关键字:work won My clear localStorage      更新时间:2023-09-26

我正在尝试用localStorage制作一个简单的程序。我创建了一个按钮来重置localStorage中的所有数据。不幸的是,我不知道为什么它不起作用。

这是我的代码:

<script>
    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('slot').innerText = "FULL";
            document.getElementById("button1").style.display = "none";
        }
    }
    document.getElementById("button1").onclick = reduceSlot;
    function clearLocalStorage(){
        localStorage.clear();
    }
</script>
<body>
    <p id="slot">10</p>
    <a href="javascript:reduceSlot(1)" id="button1">Deduct</a>
    <button onclick="clearLocalStorage()">Clear All</button>
</body>

我在网站中遵循了此代码,但它没有运行。我浏览的大多数网站都令人困惑。我需要帮助。

<button onclick="window.localStorage.clear();">Clear All</button>

这应该有效。