[英]how can i get get the delete button to remove a single item from local storage
[英]How can i delete particular item stored inside local storage?
存儲在本地存儲中的值
{"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和值,並希望在用戶提交表單時刪除具有真實值的復選框ID。
使用上面使用的方法,我無法刪除數據。 我的代碼有什么問題嗎?
在將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
為了從localStorage刪除項目,您必須使用removeItem()
函數,但實際上您需要對其進行更新。 所以首先,您必須覆蓋現有值。 請參見下面的代碼。 這是小提琴
//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.