单击按钮时,我需要更新值,但是它不起作用。我只得到空数组。
var title = form.title.value;
var data = form.date.value;
var priority = form.priority.value;
var description = form.textarea.value;
var check = form.check.value;
document.querySelector("button").addEventListener('click', function() {
var obj = {};
var arr = [];
obj.title = title;
obj.date = data;
obj.priority = priority;
obj.description = description;
obj.check = check;
arr.push(obj);
localStorage.setItem('todo_list', JSON.stringify(arr));
var tasks = JSON.parse( localStorage.getItem('todo_list') );
console.log(tasks);
});
最佳答案
您在首次运行代码时(大概是在页面加载时)正在获取所有表单值。单击按钮后,您是否应该获取它们?删除顶部的所有五个var
语句,然后直接在click
事件侦听器内部获取表单值:
document.querySelector("button").addEventListener('click', function() {
var obj = {};
var arr = [];
obj.title = form.title.value;
obj.date = form.date.value;
obj.priority = form.priority.value;
obj.description = form.textarea.value;
obj.check = form.check.value;
arr.push(obj);
localStorage.setItem('todo_list', JSON.stringify(arr));
var tasks = JSON.parse( localStorage.getItem('todo_list') );
console.log(tasks);
});
您还可以通过设置对象/数组文字内部的所有值来稍微清理代码。根据您的需求,这可能是一种更好的方法:
document.querySelector("button").addEventListener('click', function() {
var arr = [
{
title: form.title.value,
date: form.date.value,
priority: form.priority.value,
description: form.textarea.value,
check: form.check.value
}
];
localStorage.setItem('todo_list', JSON.stringify(arr));
var tasks = JSON.parse( localStorage.getItem('todo_list') );
console.log(tasks);
});