【问题标题】:localStorage not storing more than one piece of datalocalStorage 不存储多于一条数据
【发布时间】:2018-11-14 16:28:52
【问题描述】:

我正在尝试在 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 开发人员工具中,应用程序选项卡下存储了“Jones”,但没有存储“Smith”。我检查了类似的问题,但似乎都没有提供具体的解决方案。

【问题讨论】:

  • 是键值存储。如果您为同一个键提供第二个值,它将覆盖前一个值。如果您想存储多个值,则存储为逗号分隔的相同键或完全使用不同的键。

标签: javascript html local-storage


【解决方案1】:

您每次调用setItem 时都会覆盖 lastname,所以最后一个(保存"Jones")获胜。

如果您想保存多个项目,则:

  1. 使用不同的密钥(lastname1lastname2、...),或者

  2. 以某种格式存储字符串,您可以将其解析为单个项目,例如存储时 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 是一个运算符,而不是一个函数。不需要在其操作数周围加上括号。)

【讨论】:

    猜你喜欢
    • 2020-09-25
    • 2023-03-07
    • 1970-01-01
    • 2013-06-19
    • 1970-01-01
    • 1970-01-01
    • 2014-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多