【问题标题】:How to clear localStorage on button click如何在单击按钮时清除 localStorage
【发布时间】:2021-12-19 10:46:00
【问题描述】:

我按照 Youtube 上关于 localStorage 的教程进行操作,一切顺利。之后我试图搞乱这些概念并想添加一个按钮来删除 localStorage (id ="btnClear")。

现在我已经尝试了一切,但它不允许我删除存储。我认为这是因为我在函数内部声明了常量,我可能必须将它们存储在外部某处并对输入进行字符串化。但是即使在这种情况下,我也可以以某种方式清除 localStorage 吗?

<body>
<content>
      <fieldset>
        <legend>Insert Data</legend>
        <input type="text" id="inpKey" placeholder="Insert Key.." />
        <input type="text" id="inpValue" placeholder="Insert Value.." />
        <button type="button" id="btnInsert">Insert</button>
      </fieldset>
      <fieldset>
        <legend>Local Storage</legend>
        <div id="lsOutput"></div>
        <br />
        <button type="button" id="btnClear">Clear</button>
      </fieldset>
    </content>
  </body>
  <script type="text/javascript">
    const inpKey = document.getElementById("inpKey");
    const inpValue = document.getElementById("inpValue");
    const btnInsert = document.getElementById("btnInsert");
    const lsOutput = document.getElementById("lsOutput");
    const btnClear = document.getElementById("btnClear");

    btnInsert.onclick = function () {
      const key = inpKey.value;
      const value = inpValue.value;

      if (key && value) {
        localStorage.setItem(key, value);
        location.reload();
      }
    };

    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i);
      const value = localStorage.getItem(key);
      lsOutput.innerHTML += `${key}: ${value}`;
    }

    //BUTTON CLEAR

    btnClear.onclick = function () {
      localStorage.clear();
    };
  </script>

【问题讨论】:

  • 是否调用了 btnClear.onclick 函数,你检查了吗?
  • 尝试将它(脚本)放入document.ready
  • 请看我的回答,这样可以节省一些打字时间!

标签: javascript function local-storage


【解决方案1】:

在浏览器中检查您的本地存储。您的代码实际上确实清除了 localStorage。您缺少的是更新您的用户界面。将您的 Button 清除代码替换为:

btnClear.onclick = function () {
   localStorage.clear();
   if(localStorage.length === 0)
      lsOutput.innerHTML = "";
};

这是一个如何检查本地存储的教程,例如:How to view or edit localStorage

【讨论】:

    【解决方案2】:

    看看这里,我已经将你所有的代码从 HTML 更新为 JS。

    你可以测试它on jsfiddle,因为 stackoverflow 会抛出这个错误:

    {
      "message": "Uncaught SecurityError: Failed to read the 'localStorage' property from 'Window': The document is sandboxed and lacks the 'allow-same-origin' flag.",
      "filename": "https://stacksnippets.net/js",
      "lineno": 37,
      "colno": 33
    }
    

    另外,最好在您的大多数活动中使用document.addEventListener(因为它们可以为您提供到达者体验)

    查看更多活动here 来自此 URL 的引用:

    内联事件的显着缺点是与事件不同 如上所述的侦听器,您可能只有一个内联事件 分配的。内联事件存储为 元素[doc], 意味着它可以被覆盖。

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <title>How to clear localStorage on button click</title>
    </head>
    
    <body>
    
        <content>
            <fieldset>
                <legend>Insert Data</legend>
                <input type="text" id="inpKey" placeholder="Insert Key.." />
                <input type="text" id="inpValue" placeholder="Insert Value.." />
                <button type="button" id="btnInsert">Insert</button>
            </fieldset>
            <fieldset>
                <legend>Local Storage</legend>
                <ul id="outputList"></ul>
                <br />
                <button type="button" id="btnClear">Clear</button>
            </fieldset>
        </content>
    
        <script type="text/javascript">
            const printLSContent = function (el) {
                for (let i = 0; i < localStorage.length; i++) {
                    let key = localStorage.key(i);
                    let value = localStorage.getItem(key);
                    let li = document.createElement('li');
                    li.innerHTML = `K: ${key}; V: ${value}`;
                    el.appendChild(li);
                }
            }
            document.addEventListener("DOMContentLoaded", function (event) {
                const inpKey = document.getElementById("inpKey");
                const inpValue = document.getElementById("inpValue");
                const btnInsert = document.getElementById("btnInsert");
                const outputList = document.getElementById("outputList");
                const btnClear = document.getElementById("btnClear");
                // element.addEventListener(event, handler[, options]); // type - event type; listener - event handler; options -
                btnInsert.addEventListener('click', function () {
                    const key = inpKey.value;
                    const value = inpValue.value;
                    localStorage.setItem(key, value);
                    location.reload();
                }, false);
                printLSContent(outputList);
    
                // //BUTTON CLEAR
                btnClear.addEventListener('click', function () {
                    localStorage.clear();
                    location.reload();
                }, false);
            });
        </script>
    </body>
    
    </html>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-21
      • 2019-12-17
      • 2012-02-04
      • 2017-05-17
      • 1970-01-01
      • 2017-05-06
      相关资源
      最近更新 更多