页面刷新后本地存储出现问题。数组为空

问题描述 投票:0回答:2

好吧,我迷路了。我已经尝试了所有(或者看起来是这样)。我是 javascript 的新手,我正在尝试将输入数据保存到数组中,然后保存到本地存储中。它工作正常,直到我刷新页面,然后数组为空并且数据丢失。

有人可以帮忙吗?

这是我的代码。其实很简单。


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
<input id="input-id-first-name" value="Frontname">
<button id="btn">Send value</button>
<p id="output"></p>

</body>
<script>
    const inputFirstNameEl = document.querySelector("#input-id-first-name");
    const btnEl = document.querySelector("#btn");
    const outputEl = document.querySelector("#output");

    
    const array = []
    
    let getStorage = JSON.parse(localStorage.getItem("storage"))
    btnEl.addEventListener("click", getInput);
    
    function getInput () {
        localStorage.setItem("storage", JSON.stringify(array));
        const getInputFirst = inputFirstNameEl.value;
        array.push(getInputFirst);  
        
    }
    
    console.log(JSON.parse(localStorage.getItem("storage")));

</script>
</html>

local-storage
2个回答
0
投票

问题是,您的 localStorage 中有数据,页面刷新后数据丢失,无法在我的机器上重现。

但也许这就是问题的一部分:

const array = []
...
function getInput () {
   localStorage.setItem("storage", JSON.stringify(array)) // write current content of array to localStorage
   const getInputFirst = inputFirstNameEl.value
   array.push(getInputFirst) // add input of textfield to array
}

因此,您将空数组的内容写入 localStorage,然后将文本字段的内容添加到数组中。

localStorage.setItem("storage", JSON.stringify(array))
放在函数末尾。

另一个提示,请使用浏览器的开发工具 (F12)。以 Chrome 为例,在“应用程序”选项卡中,您可以查看 localStorage 中的实际内容。也许比只有

console.log
更好。


0
投票

找到答案或者解决了吗?怎么办?

© www.soinside.com 2019 - 2024. All rights reserved.