[英]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.