【问题标题】:How can i delete particular item stored inside local storage?如何删除存储在本地存储中的特定项目?
【发布时间】:2017-07-07 16:33:29
【问题描述】:

存储在本地存储中的值

{"10":true,"11":true,"16":false}

我想删除存储在本地存储中的特定数据,例如10

var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {};

$.each(checkboxValues, function(key, value) {
                if(value===true) {
                    delete checkboxValues[key];
                    }
                }
            });

我在 onload 期间存储了所有复选框 id 和值,并希望在用户提交表单时删除那些具有 true 值的复选框 id。

使用上述方法,我无法删除数据。我的代码有什么问题吗?

【问题讨论】:

    标签: javascript local-storage


    【解决方案1】:

    为了从 localStorage 中删除项目,您必须使用 removeItem() 函数,但在您的情况下,您实际上需要更新它。所以首先你必须覆盖现有的值。请参阅下面的代码。这是Fiddle

    //set the value for first time suppose
    localStorage.setItem("checkboxValues", JSON.stringify({
      "10": true,
      "11": true,
      "16": false
    }));
       //get the value and update
    var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {};
    $.each(checkboxValues, function(key, value) {
      if (value === true) {
        delete checkboxValues[key];
      }
    })
       //store the updated value back to localStorage
    localStorage.setItem("checkboxValues", JSON.stringify(checkboxValues));
    console.log(JSON.stringify(checkboxValues));//logs {"16":false}
    console.log(JSON.parse(localStorage.getItem('checkboxValues')));
    // logs an object with only one property {16:false}

    【讨论】:

      【解决方案2】:

      在将json对象保存到localstorage之前,请将json对象转换为字符串,然后像这样存储在localstorage中

      JSON.stringify({"10":true,"11":true,"16":false});
      

      然后你在哪里解析它可以正常工作,只是在保存时请将 json 对象转换为字符串 这是更新的代码

      var jsonData = JSON.stringify({"10":true,"11":true,"16":false});
      localStorage.setItem('checkboxValues', jsonData);
      
      var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {};
      
      $.each(checkboxValues, function(key, value) {
          if(value===true) {
              delete checkboxValues[key];
          }
      });
      

      这里显示它工作正常 https://iamlalit.tinytake.com/sf/MTc1ODUwMl81Nzc4NzMw

      【讨论】:

      • 是的,我做到了。但它不会删除特定数据。
      • 奇怪的只是复制粘贴上面的代码,就像我在你的 chrome 控制台中的屏幕截图中所做的那样,然后查看输出
      • 我在删除数据后缺少更新本地存储语句。感谢您的帮助。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-26
      • 1970-01-01
      相关资源
      最近更新 更多