Javascript 为什么不是';我的代码是否将项目存储在localStorage中?休息吧,一切都好

Javascript 为什么不是';我的代码是否将项目存储在localStorage中?休息吧,一切都好,javascript,html,Javascript,Html,此代码无法将添加的项存储到localStorage中。 但它运行良好 当我重新加载页面时,我的所有项目都会消失。 请帮忙 var list=[]; var add=document.getElementById('add'); add.addEventListener('click',function(){ var task=document.getElementById('task')。值; 列表推送(任务); setItem('todo',JSON.stringify(list)); va

此代码无法将添加的项存储到localStorage中。 但它运行良好 当我重新加载页面时,我的所有项目都会消失。 请帮忙

var list=[];
var add=document.getElementById('add');
add.addEventListener('click',function(){
var task=document.getElementById('task')。值;
列表推送(任务);
setItem('todo',JSON.stringify(list));
var todo_str=localStorage.getItem('todo');
var todos=JSON.parse(todo_str);
var html='';
对于(var i=0;i
添加
    由于列表最初为空,当单击“添加”按钮时,您正在将其保存在localStorage中,因此以前添加的所有项目都将被覆盖

    localStorage.setItem('todo', JSON.stringify(list)); // This is overriding your items from the last session
    
    如果要持久化上一个会话中的项目,可以使用localStorage而不是空数组初始化列表

    list = JSON.parse(localStorage.getItem('todo')); // This will persist your items from the last session
    

    一个一般性建议:我发现最好使用而不是
    localStorage
    您能告诉我这个问题而不是使用其他技术吗?list=JSON.parse(localStorage.getItem('todo'))| |[];嘿,伙计们,我很困惑。请让我理解,当加载页面时,localStorage包含上一个会话中的项目。然后初始化一个空列表。现在,当单击“添加”按钮时,您将一个项目添加到空列表中,因此它现在有1个项目。然后,您将localStorage的内容替换为包含1个项目的列表。这就是您的位置OOS上一个会话的数据。我们建议使用localStorage的内容初始化列表(如果存在)。因此,现在,当您添加项时,它将附加到上一个会话的项中,而不是覆盖它们。