2017-10-17 28 views
1

我試圖在localStorage中保存一些數據。但每次刷新頁面時都會覆蓋舊數據上的新數據,並丟失舊數據。如何停止覆蓋localStorage中的數據

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

店內我的數據就像這段代碼。它工作正常,但當我刷新頁面數據消失了。
p.s. testblockchain是一個類。

+1

每次刷新頁面'testshod'函數被調用時,這就是您的數據被覆蓋的原因。你可以嘗試使用'if'條件來檢查你的'localStorage'中是否已經有一些數據,如果'true'沒有設置它,而只是取回它。 – Krusader

+0

先檢查localStorage是否已經有東西,如果localStorage爲空則寫入 –

+0

您正在使用哪種瀏覽器?在編寫之前,您還沒有檢查數據 – Mudassar

回答

2

您應該檢查是否已經存在的localStorage

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

如果要更新哈希給定的時間後,你也應該存儲在localStorage的最後更新的時間,檢查過的值。