簡體   English   中英

Localstorage 只保存最后一個 object (vanilla Javscript)

[英]Localstorage saves only last object (vanilla Javscript)

我想在 OOP 中制作一個帶有書單的應用程序,但是在本地存儲中保存列表時遇到問題。我讓該用戶可以添加他的書,現在我想將其保存到本地存儲中。 我制作了一個數組,並將對象保存到其中,但有些東西不起作用。 我只得到最新的 object,我不知道為什么。

一塊js:

    var title = document.querySelector('input#title').value;
    var author = document.querySelector('input#author').value;
    var status = document.querySelector('select').value;
    var table = document.querySelectorAll('.table')[1];
    var book = new Book(title, author, status);
    obj.push(book);
    localStorage.setItem('Array',JSON.stringify(obj));

您正在使用鍵“Array”覆蓋先前的 localStorage 項目。

Storage 接口的setItem()方法,當傳遞一個鍵名和值時,會將該鍵添加到給定的 Storage object,或者如果該鍵的值已經存在,則更新該鍵的值,因此在您的情況下將更新以前的 localstorage 項。 . 如果你想解決它,你需要使用之前嘗試的值,你需要使用一個唯一的鍵。 也許有運行ID的東西

localStorage.setItem(`Array-${id}`,JSON.stringify(obj));

由於每次使用 setItem 時都使用相同的鍵,localStorage 將覆蓋該值。 我認為您遇到的問題與您如何初始化 obj 數組有關。 如果您有一個 function 將書籍列表/數組保存到 localStorage,那么請確保在 function 之外初始化 obj。 看看下面的例子。

function Book(title, author, status) {
  this.title = title;
  this.author = author;
  this.status = status;
}

var obj = []; // <- initialize obj array here instead

function addBook(title, author, status) {
  // var obj = []; <- if obj is initialized within the function it will be a new empty array every time, which is why localStorage only shows the latest item.

  var book = new Book(title, author, status);

  obj.push(book);

  localStorage.setItem('Array', JSON.stringify(obj));
}

addBook('Harry Potter: Order of Phoenix', 'JK Rowling', 'Available')

確保您使用以前的值初始化obj

let obj = JSON.parse(localStorage.getItem('Array'));
...

做一些事情,比如從你的本地獲取 Array 值,然后在那里添加項目。

 const array = JSON.parse(localStorage.getItem('Array')) || []; class Book { constructor(title, author, status) { this.title = title; this.author = author; this.status = status; } } document.getElementById("push_item").addEventListener("click", function() { console.log("push"); var title = document.querySelector('input#title').value; var author = document.querySelector('input#author').value; var status = document.querySelector('select').value; var table = document.querySelectorAll('.table')[1]; var book = new Book(title, author, status); array.push(book); localStorage.setItem('Array', JSON.stringify(array)); });
 <input id="title"></input> <input id="author"></input> <select > <option value="1"/>1 <option value="2"/>2 </select> <button id="push_item">Push</button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM