簡體   English   中英

將對象數組添加到 javascript 中的本地存儲?

[英]Adding an array of objects to local storage in javascript?

嘗試將一組對象保存到 localStorage 中,然后將其取回。

由於某種原因,在控制台中新的 arr 是空的 (history = []) 而在 localStorage 中,savedgameHistory = [{},{}]

*對不起,我沒有正確解釋自己。 我需要保存數組順序。 為了在 UNDO 按鈕中使用它。


const img1 = document.getElementById("img1"); // img tag
const img2 = document.getElementById("img2"); // img tag

let arrOfObj = [img1, img2]

function saveGame(){
localStorage.setItem("savedgameHistory", JSON.stringify(arrOfObj));
window.location.href = "./TicTacToe.html";
}

function loadGame(){
 const history = JSON.parse(localStorage.getItem("savedgameHistory"));
}

本地存儲中不保存圖片標簽,而是保存一個字符串,要保存的字符串是圖片的src屬性,所以保存如下:

 const img1 = document.getElementById("img1"); // img tag const img2 = document.getElementById("img2"); // img tag let arrOfObj = [img1.src, img2.src] function saveGame() { localStorage.setItem("savedgamehistory", JSON.stringify(arrOfObj)); window.location.href = "./TicTacToe.html"; } function loadGame() { const history = JSON.parse(localStorage.getItem("savedgameHistory")); }

然后,加載后,將其視為 src 字符串,因此將其直接放在 html 文件中的圖像標簽上,例如:

<img id="img1" />
<img id="img2" />
function loadGame() {
  const history = JSON.parse(localStorage.getItem("savedgameHistory"));
  img1.src = history[0]  
  img2.src = history[1]
}

暫無
暫無

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

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