2017-07-07 139 views
1

如何删除本地存储器内存储的特定项目?里面存放的本地存储

{"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]; 
        } 
       } 
      }); 

我存储所有的复选框的id和值在onload事件,并希望删除这些复选框ID与真实值当用户提交表单。

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

回答

0

为了从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}

+0

谢谢,它的工作原理。 – Crazy

+0

不客气。乐于帮助 :) – Manish

0

节省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

+0

是的,我做到了。但它不会删除特定的数据。 – Crazy

+0

奇怪的只是复制粘贴上面的代码,因为我在我的屏幕截图中在你的Chrome控制台中看到了输出 –

+0

我在删除数据后缺少更新本地存储语句。感谢帮助。 – Crazy