简体   繁体   English

如何删除存储在本地存储中的特定项目?

[英]How can i delete particular item stored inside local storage?

Values stored inside local storage 存储在本地存储中的值

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

I want to delete a particular data stored inside local storage eg 10 我想删除存储在本地存储中的特定数据,例如10

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

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

I stored all checkboxes id and value during onload, and want to remove those checkboxes id with true value when user submit the form. 我在onload期间存储了所有复选框ID和值,并希望在用户提交表单时删除具有真实值的复选框ID。

With the method used above, I unable to delete the data. 使用上面使用的方法,我无法删除数据。 Is anything wrong with my code? 我的代码有什么问题吗?

before saving json object into the localstorage please convert the json object into string and then store it in localstorage like this 在将json对象保存到localstorage之前,请先将json对象转换为字符串,然后像这样将其存储在localstorage中

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

and then where you are parsing things it works correctly, just on saving please convert json object into string here is the updated code 然后在您解析的东西正常工作的地方,只需保存,请将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];
    }
});

here it is showing it working fine https://iamlalit.tinytake.com/sf/MTc1ODUwMl81Nzc4NzMw 在这里它显示它工作正常https://iamlalit.tinytake.com/sf/MTc1ODUwMl81Nzc4NzMw

In order to delete an item from localStorage you have to use removeItem() function but in your case you actually need to update it. 为了从localStorage删除项目,您必须使用removeItem()函数,但实际上您需要对其进行更新。 So first so you have to overwrite the existing value. 所以首先,您必须覆盖现有值。 See the code below. 请参见下面的代码。 Here is a 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} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM