如何停止覆盖localStorage中的数据

时间:2017-10-17 08:20:12

标签: javascript html5 local-storage

我正在尝试在localStorage中保存一些数据。但每次刷新页面时,新数据都会覆盖旧数据并丢失旧数据。

function testshod() {
    localStorage.setItem("hash", JSON.stringify(testblockchain));
    document.getElementById("result").innerHTML = 
    localStorage.getItem("hash");
    }

存储我的数据,如此代码。它工作正常,但当我刷新页面数据消失。
附: testblockchain是一个类。

1 个答案:

答案 0 :(得分:2)

您应该检查localStorage中是否已有值

function testshod() {
    if (!localStorage.getItem("hash")) {
        localStorage.setItem("hash", JSON.stringify(testblockchain));
    }
    document.getElementById("result").innerHTML = localStorage.getItem("hash");
}

如果您想在给定时间后更新哈希值,您还应该将最后更新的时间存储在localStorage中并检查它。

相关问题