2017-07-07 108 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