[英]localStorage not storing more than one piece of data
I'm trying to store multiple pieces of data in localStorage. 我正在尝试在localStorage中存储多个数据。 However, only one piece is being stored and I can't figure out why.
但是,只存储了一件,我不知道为什么。 Here's the code
这是代码
<!DOCTYPE html>
<html>
<body>
<div id="result"></div>
<div id="result2"></div>
<script>
if (typeof(Storage) !== "undefined") {
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML =
localStorage.getItem("lastname");
}
if (typeof(Storage) !== "undefined") {
// Store
localStorage.setItem("lastname", "Jones");
// Retrieve
document.getElementById("result2").innerHTML =
localStorage.getItem("lastname");
}
</script>
</body>
</html>
In Chrome Developer tools, under the application tab "Jones" is stored but "Smith" is not. 在Chrome Developer工具中,在应用程序标签下存储了“琼斯”,但未存储“史密斯”。 I have checked similar questions, but none seem to provide a specific solution.
我检查了类似的问题,但似乎没有一个提供特定的解决方案。
You're overwriting lastname
every time you call setItem
, so the last one (saving "Jones"
) wins. 每次调用
setItem
,您都将覆盖 lastname
,因此最后一个(保存"Jones"
)将获胜。
If you want to save more than one item, either: 如果要保存多个项目,请执行以下任一操作:
Use a different key ( lastname1
, lastname2
, ...), or 使用其他密钥(
lastname1
, lastname2
,...)或
Store a string in some format you can parse into individual items, for instance an array that you JSON.stringify
when storing and JSON.parse
when loading 以可以解析为单个项目的某种格式存储字符串,例如,存储时为
JSON.stringify
的数组, JSON.stringify
时为JSON.parse
的数组
Side note: Sadly, that typeof
check is not adequate to determine whether you can use localStorage
, because on some browsers in private browsing mode, typeof
will say it's there but it'll throw an error when you try to save something. 旁注:遗憾的是,这种
typeof
检查不足以确定您是否可以使用localStorage
,因为在某些处于私有浏览模式的浏览器中, typeof
会说它在那里,但是在您尝试保存内容时会抛出错误。 The only way to know for sure is to actually try to save something: 唯一可以确定的方法是实际尝试保存一些东西:
// Once on page load
const canUseStorage = typeof localStorage !== "undefined" && (() {
const key = "_test_storage";
const now = String(Date.now());
try {
localStorage.setItem(key, now);
const flag = localStorage.getItem(key) === now;
try {
localStorage.removeItem(key);
} catch (e) {
}
return flag;
} catch (e) {
return false;
}
})();
// Then use `canUseStorage` as necessary to decide if you can use it
(Also note that typeof
is an operator, not a function. No need for parens around its operand.) (还请注意,
typeof
是运算符,而不是函数。不需要在其操作数周围加括号。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.