javascript - 如何通过 vanilla JS 保存到本地存储
问题描述
我似乎无法让本地存储工作。目标是在刷新时将待办事项列表项保留在页面上。每次我刷新页面它都会噗。语法似乎正确。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TODO LIST</title>
<link rel="stylesheet" href="./styles/style.css">
</head>
<body>
<main id="main">
<h1>THE TO-DO LIST:</h1>
<form action="" id="add-task">
<label for="todo">Add Task:</label>
<input type="text" id="todo">
<button>Add Task</button>
</form>
<p class="center">To complete task, click on text.</p>
<ul id="task-list">
<li class="task-complete">example_1 <button>Remove Task</button></li>
</ul>
</main>
<script src="./script/index.js"></script>
</body>
</html>
const form = document.querySelector('#add-task');
const input = document.querySelector('#todo');
const taskList = document.querySelector('#task-list');
let taskID = 0;
taskList.addEventListener('click', function(e) {
if (e.target.tagName === 'BUTTON') {
e.target.parentElement.remove();
let inputTask = document.getElementById('todo');
localStorage.setItem('email', inputTask.value);
} else if (e.target.tagName === 'LI') {
e.target.classList.toggle('task-complete');
}
});
form.addEventListener('submit', function(e) {
e.preventDefault();
console.log(input.value);
const newTask = document.createElement('li');
const removeBtn = document.createElement('button');
let savedInput = input.value;
removeBtn.innerText = 'Remove Task';
newTask.innerText = input.value;
newTask.appendChild(removeBtn);
taskList.appendChild(newTask);
input.value = '';
console.log(localStorage);
});
.task-complete {
text-decoration: line-through;
}
解决方案
约书亚,从您的样本中可以看出以下几点:
- 首先,您将
localStorage
使用当前输入值设置为单个项目,而不是像数组这样的任务集合 - 似乎您在重新加载页面时没有获得保存的数据,这就是为什么页面重新加载时没有任何反应
- 请记住,您只能将字符串保存到
localStorage
,在待办事项列表中您可能想要保存一个数组(待办事项的集合),但由于您不能这样做,您需要在保存时将其转换为字符串 (JSON.stringify(yourArray)
将帮助您那),并在加载时将其解析回一个数组(JSON.parse
)
const form = document.querySelector('#add-task');
const input = document.querySelector('#todo');
const taskList = document.querySelector('#task-list');
let taskID = 0;
let tasks = [] // here will hold your current todos collection
// a function that will retrieve the saved todos from local storage
//
// note that 'tasks' can be any string identifier that you want — 'todos'
// would also work — but you need to use the same for localStorage.getItem
// and localStorage.setItem
function getTasksFromLocalStorage(){
// it will return `null` if nothing's there
tasks = localStorage.getItem('tasks') || []
if (tasks) {
// convert it to an array so you can loop over it
tasks = JSON.parse(tasks)
}
}
function addTask(text) {
// CREATE DOM ELEMENTS
const newTask = document.createElement('li');
const removeBtn = document.createElement('button');
removeBtn.innerText = 'Remove Task';
// set the text to the provided value
newTask.innerText = text;
// append the remove button
newTask.appendChild(removeBtn);
// append it to the dom so we can see it
taskList.appendChild(newTask)
}
// on page load get tasks from local storage
// then loop over it, create the DOM elements and append them to
// the taskList
document.addEventListener('DOMContentLoaded', function() {
getTasksFromLocalStorage()
// if we have saved tasks, loop over them and render to the dom
tasks.forEach(function(savedTaskText) {
addTask(savedTaskText)
})
})
// then on your code, you need to update to push
// the current inputed `task` to the `tasks` collection (Array)
// then save the entire collection to the local storage
// then add the new task to the DOM
// and finally reset the input
form.addEventListener('submit', function(e) {
e.preventDefault();
console.log(input.value);
// save it to the current holding list
tasks.push(input.value)
// save a copy of the updated list to the localStorage, so when you
// reload the page you get saved items!
localStorage.setItem('tasks', tasks)
// add it to DOM
addTask(input.value);
// reset the input
input.value = '';
});
如果您希望任务具有唯一的 ID(因为,您可以稍后删除它们),您需要做更多的事情,但是为了解释的简洁,代码被简化(但无论如何您得到了一个很长的答案)。
这是如此文档和建议阅读:
- LocalStorage 的 MDN 文档
- JSON 的 MDN 文档(解析和字符串化)
- 有很多 vanilla javascript 教程(书面和 youtube)用于“使用 localStorage 创建待办事项列表”,它们比我们在 SO 答案中所能提供的更详细,我建议您也浏览一下!
祝你好运,编码快乐✌️
推荐阅读
- python - 返回一个不带括号的二维数组
- postgresql - 将 SQL 字符串添加到 EF Core LINQ(附加 ZQL 查询)
- html - 我在这里犯了什么错误?
- sql - SQL 括号
- python - [featuretools]“EntitySet”对象没有属性“entity_from_dataframe”
- r - 如何将 R 图形设备设置为二维画布?
- android-studio - 在 Kotlin 中显示日期而不是变量
- tensorflow - 我正在尝试将 TensorflowMicro 缓冲区数组存储和检索为 Arduino MBED SDRAM 指针
- python - Pandas to_sql to redshift 指定列编码
- python - win32com DispatchEx 返回无效的类字符串