如何从本地存储阵列中删除特定项目?

时间:2017-07-05 08:43:40

标签: javascript arrays local-storage

我正在建立一个待办事项列表' ,用户在单击后将新注释添加到列表中。

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

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

    **//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 个答案:

答案 0 :(得分:0)

正如评论中所述,您只需提供相关代码,但只是为了清除这里的内容,这里的方法是:

  • 要有一个空数组notes
  • 通过localStorage将此数组添加到localStorage.setItem("savedNotes", JSON.stringify(notes))
  • 每次添加注释时,您都需要:使用localStoragenotes = JSON.parse(localStorage.getItem("savedNotes"))解析此数组。
  • 然后通过note将新的notes.push(note)推送到此数组中。
  • 然后使用localStorage.setItem("savedNotes", JSON.stringify(notes))重新设置此项目,它将更新localStorage中的现有项目。

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

要从数组中删除note,您需要执行相同的操作,期望您将在已解析的数组中搜索此注释并将其删除。

相关问题