0

我正在尝试使用以下代码在一个页面上的本地存储中设置一个项目:

localStorage.setItem("move1s", JSON.stringify(document.getElementById("move1").textContent));

当我尝试使用以下代码检索它时,它说它返回一个空错误:

document.getElementById("specNickname").textContent = JSON.parse(localStorage.getItem("move1s"));

这很奇怪,因为当我尝试执行以下操作时,它打印出来的效果非常好,所以很明显密钥是可识别的:

console.log(localStorage.getItem("move1s"));

我知道我使用 localStorage 错误,但我不知道我具体做错了什么。如果需要发布更多代码,请告诉我。先感谢您。

4

2 回答 2

1

如果您想要一个示例,如何使用本地存储:

保存

aObj = {name: "TEST",city: "LONDON"};

aJSON = JSON.stringify(myObj);

localStorage.setItem("testJSON", myJSON);

检索

text = localStorage.getItem("testJSON");

obj = JSON.parse(text);

document.getElementById("example").innerHTML = obj.name;
于 2021-02-27T09:02:42.337 回答
1
localStorage.setItem("move1s", JSON.stringify(document.getElementById("move1").textContent)); 

=> "Text in node"

JSON.parse 需要一个 JSON 对象,而不是 JSON 格式的字符串。您应该在控制台中看到的错误类似于

Uncaught SyntaxError: Unexpected token T in JSON at position 0
    at JSON.parse (<anonymous>)

因为它看到的第一个字符是 Text 中的 T。您需要将文本包装在大括号中以进行字符串化,{}并使其成为有效的 JSON 对象以重新解析

var move1s = {(document.getElementById("move1").textContent))}

localStorage.setItem("move1s", JSON.stringify(move1s)}; 

=> {"Text in node"}

于 2021-02-27T09:17:37.543 回答