2017-07-05 93 views
0

我正在构建'待办事项列表',用户在点击后将新笔记添加到列表中。如何从本地存储阵列中删除特定项目?

我将所有附加数据保存在本地存储中。

现在我想从数组中删除单击的注释并将其保存回本地存储。 我有这样的代码:

**//Here i get the note** 
    var getNote = JSON.parse(localStorage.getItem("savedNotes")) || []; 
     $("#notes-section").append(getNote); 

    **//Here i set the note** 
     getNote.push(note); 
     localStorage.setItem("savedNotes", JSON.stringify(getNote)); 



**//Here i want to remove the note from the array** 
    $(document).on('click', '.pin', function() { 
$(this).parent().css({opacity: 1.0, visibility: "visible"}).animate({opacity: 0}, 2000); 

    for(var i =0 ; i < getNote.length; i++){ 

    getNote.splice(i,1); 


     localStorage.setItem("savedNotes", JSON.stringify(getNote)); 
    } 

}); 
+1

你能把你的代码缩小到_ [mcve] _吗?重视最低限度。 – evolutionxbox

+0

@evolutionxbox谢谢,现在它的o.k? (我是新来的..) –

+0

好多了。显示该问题的较短示例可帮助人们更快更准确地回答您的问题。 – evolutionxbox

回答

0

正如评论说您只需要提供相关的代码,而只是在这里清楚的事情了,去这里的方法是:

  • 必须有一个空数组notes
  • 将此阵列添加到localStorage通过localStorage.setItem("savedNotes", JSON.stringify(notes))
  • 每次添加便条时,您都需要:将该数组从localStorage解析为notes = JSON.parse(localStorage.getItem("savedNotes"))
  • 然后通过notes.push(note)将新的note推入此阵列。
  • 然后用localStorage.setItem("savedNotes", JSON.stringify(notes))再次设置此项目,它会更新您在localStorage中的现有项目。

这一切都依赖于Storage.getItem()Storage.setItem()方法。

而要从数组中删除note,您需要做同样的事情,期望您将在解析的数组中搜索此笔记并将其删除。

+0

感谢您的回答,但我仍然无法弄清楚如何做到这一点,你能更具体吗? –

+0

你需要遍历数组,找到要从数组中删除它的项,你可以按照[this](https://stackoverflow.com/q/10024866/3669624)。 –