繁体   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