为类项目创建待办事项列表 - 能够将项目“添加”并追加到列表中,但是当您刷新页面时,该项目将返回为 undefined
。检查 localStorage.todo
,我发现它提取了我需要的部分值,但尚未使用,但不是实际的 innerText
。我开始添加用于直通的位以检查已完成的项目和删除按钮,但这已被注释掉,希望不会影响事情 - 正在尝试隔离错误。
我猜我的问题出在 localStorage.setItem
中,但我不确定它是什么。我尝试将 newTodo.innerText 值更改为正在使用的其他变量,但没有任何返回。下面返回我输入的输入值,但在页面刷新时再次丢失。
const todoForm = document.querySelector('#todoForm');
const todoList = document.querySelector('#todoList');
let todoItem = document.querySelector('#todoItem');
// Pull from storage
const savedList = JSON.parse(localStorage.getItem('todo')) || [];
for (let i = 0; i < savedList.length; i++)
{
let newTodo = document.createElement('li');
newTodo.innerText = savedList[i].task;
todoList.appendChild(newTodo);
}
// Add Item
todoForm.addEventListener('submit', function(e){
e.preventDefault();
let newTodo = document.createElement('li');
let newItem = document.querySelector('#todoItem').value;
newTodo.innerText = newItem;
todoForm.reset();
todoList.appendChild(newTodo);
// Clear Form Field on submit and storage
savedList.push({ task: newTodo.innertext, isCompleted: false });
localStorage.setItem('todo', JSON.stringify(savedList));
});
// Add Remove Button
// let removeItem = document.createElement('button');
// removeItem.innerText = "Remove";
// newTodo.append(removeItem);
// Strike through item or remove item
// todoList.addEventListener('click', function(e){
// if (e.target.tagName === 'BUTTON'){
// e.target.parentElement.remove();
// }
// else if (e.target.tagName === 'LI'){
// e.target.style.textDecoration = 'line-through';
// }
// });
最佳答案
camelcase 错误的不是 innertext
而是 innerText
savedList.push({ task: newTodo.innerText, isCompleted: false })
关于Javascript:无法从本地存储中提取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68786562/