[英]How can i delete specific item from LocalStorage
我的本地商店有很多價值,我想刪除其中的一些。 當我單擊創建的動態卡時,應正常和在本地將其刪除。 我通常可以刪除它,但不能從本地刪除它。
本地存儲事件非常令人困惑,並且沒有很多說明性資源。 至少我找不到它。 謝謝您的幫助。
$('#field').keypress(function (e) { if (e.keyCode === 13 && !e.shiftKey) { e.preventDefault(); if ($('#field').val() === '') return false; let comment = { card: $('#field').val(), id: generateGUID() }; $('#field').val('') var store = JSON.parse(localStorage.getItem('todo')) || []; store.push(comment); localStorage.setItem('todo', JSON.stringify(store)); $(this).val(''); displayComment(comment); } }); function displayComment(comment) { var html = $(`<div class="card" data-id="${comment.id}"><h5>${comment.card}</h5></div>`); $('.yorum').append(html); $('.yorum').find(html).click(function () { $(html).remove(); }); } var store = JSON.parse(localStorage.getItem('todo')) || []; store.forEach(displayComment);
嘗試使用localStorage
對象的localStorage.removeItem('ITEM_NAME')
方法。
這是在localStorage
中創建,獲取和刪除項目的示例
localStorage.setItem('aaa','1231') //undefined
localStorage.getItem('aaa') //"1231"
localStorage.removeItem('aaa') //undefined
localStorage.getItem('aaa') //null
這是您的情況的代碼示例:
function displayComment(comment) {
var html = $(`<div class="card" data-id="${comment.id}"><h5>${comment.card}</h5></div>`);
$('.yorum').append(html);
$('.yorum').find(html).click(function () {
$(html).remove();
var arr = JSON.parse(localStorage.getItem('todo'));
for(var i=0;i<arr.length;i++)
{
if(arr[i].id=this.getAttribute('data-id'))
{
arr.splice(i,1);
break;
}
}
localStorage.setItem('todo', JSON.stringify(arr));
});
}
在點擊處理程序內部,您還必須獲取已解析的本地存儲值,然后調用splice(index,1),將條目號作為“ index”傳遞。
就像是...
$('#field').keypress(function (e) { if (e.keyCode === 13 && !e.shiftKey) { e.preventDefault(); if ($('#field').val() === '') return false; let comment = { card: $('#field').val(), id: generateGUID() }; $('#field').val('') var store = JSON.parse(localStorage.getItem('todo')) || []; store.push(comment); localStorage.setItem('todo', JSON.stringify(store)); $(this).val(''); displayComment(comment, store.length-1); } }); function displayComment(comment, index) { var html = $(`<div class="card" data-id="${comment.id}"><h5>${comment.card}</h5></div>`); $('.yorum').append(html); $('.yorum').find(html).click(function () { $(html).remove(); var store = JSON.parse(localStorage.getItem('todo')) || []; store.splice(index, 1); localStorage.setItem('todo', JSON.stringify(store)); }); } var store = JSON.parse(localStorage.getItem('todo')) || []; store.forEach(displayComment);
localStorage.removeItem(key);
根據要求更換鑰匙
所有答案都很好。 您怎么也可以這樣:
localStorage[key] = undefined;
由於localstorage是鍵值對象
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.