如何删除列表json数组localstorage中的项目?
在localstorage示例中:
key: notes
value: ["car", "apple", "orange", "banana"]
e.g。我只想删除orange
notes
我从https://codepen.io/xszaboj/pen/dOXEey?editors=1010
获取此代码我尝试添加此函数delNote()但不能正常工作
此完整代码
function addNote(){
var data = localStorage.getItem("notes")
var notes = null;
if(data != null)
{
notes = JSON.parse(data);
}
if(notes == null){
notes = [];
}
notes.push($("#note").val());
localStorage.setItem("notes", JSON.stringify(notes));
refreshNotes();
}
function refreshNotes(){
var notesElement =$("#notes");
notesElement.empty();
var notes = JSON.parse(localStorage.getItem("notes"));
if(notes != null){
for(var i = 0; i< notes.length; i++){
var note = notes[i];
notesElement.append("<li onclick='delNote(this.innerHTML)'>"+note+"</li>");
}
}
}
function delNote(e){
var notes = JSON.parse(localStorage.getItem("notes"));
delete notes[e];refreshNotes();
}
$(function(){
refreshNotes();
$("#add").click(function(){
addNote();
});
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="note" />
<button id="add">add note</button>
<ul id="notes">
</ul>
&#13;
如何删除列表json数组localstorage中的项目?
答案 0 :(得分:0)
// Parse json
let notes = JSON.parse(localStorage.getItem("notes"))
// Get index of object
const index = notes.indexOf(obj)
// Splice the array at the index of your object
notes.splice(index, 1)
// Save back to localStorage
localStorage.setItem("notes", JSON.stringify(notes))