[英]localStorage not storing more than one piece of data
我正在尝试在localStorage中存储多个数据。 但是,只存储了一件,我不知道为什么。 这是代码
<!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>
在Chrome Developer工具中,在应用程序标签下存储了“琼斯”,但未存储“史密斯”。 我检查了类似的问题,但似乎没有一个提供特定的解决方案。
每次调用setItem
,您都将覆盖 lastname
,因此最后一个(保存"Jones"
)将获胜。
如果要保存多个项目,请执行以下任一操作:
使用其他密钥( lastname1
, lastname2
,...)或
以可以解析为单个项目的某种格式存储字符串,例如,存储时为JSON.stringify
的数组, JSON.stringify
时为JSON.parse
的数组
旁注:遗憾的是,这种typeof
检查不足以确定您是否可以使用localStorage
,因为在某些处于私有浏览模式的浏览器中, typeof
会说它在那里,但是在您尝试保存内容时会抛出错误。 唯一可以确定的方法是实际尝试保存一些东西:
// 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
(还请注意, typeof
是运算符,而不是函数。不需要在其操作数周围加括号。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.