青春因奋斗而闪光,梦想因拼搏而绽放!
你是否遇到过这样的尴尬:用户填了一半的表单,不小心刷新页面,所有内容都没了?别担心!今天我们就来学习如何让浏览器拥有“记忆”,即使用户关闭页面,数据也不会丢失!最后带大家做一个 「离线也能用的待办清单」,Let’s go!
一、浏览器三大“储物柜”
1. localStorage:永久储物柜
特点: 关掉浏览器数据还在,除非手动删除
用法:
// 存数据(键值对形式)
localStorage.setItem('username', '小明');
// 取数据
const name = localStorage.getItem('username');
// 删数据
localStorage.removeItem('username');
存对象(需用 JSON 转换):
const user = { id: 1, age: 18 };
localStorage.setItem('user', JSON.stringify(user)); // 存
const userData = JSON.parse(localStorage.getItem('user')); // 取
2. sessionStorage:临时储物柜
**特点:**仅当前标签页有效,关闭就消失
用法(和 localStorage 一样):
sessionStorage.setItem('token', 'abc123');
3. Cookie:会自动打包的小纸条
特点: 容量最小(4KB),每次请求自动发给服务器
原生操作:
// 存(注意格式)
document.cookie = 'username=小明; path=/; max-age=3600'; // 1 小时过期
// 取(需自己解析)
function getCookie(name) {
return document.cookie
.split('; ')
.find(row => row.startsWith(name))
?.split('=')[1];
}
二、选对“储物柜”的三大原则
场景 | 推荐存储 | 示例 |
---|---|---|
长期保存用户设置 | localStorage | 主题偏好、语言设置 |
临时表单数据 | sessionStorage | 多步骤表单的暂存数据 |
登录凭证 | Cookie | 用户登录态 token |
三、实战:离线待办清单
1. 功能演示
2. 完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>我的待办清单</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
<style>
body {
font-family: 'Arial', sans-serif;
background: linear-gradient(135deg, #74ebd5, #acb6e5);
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
color: #333;
}
.container {
background-color: #fff;
border-radius: 15px;
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
padding: 30px;
width: 360px;
text-align: center;
transition: all 0.3s ease;
}
.container:hover {
box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2);
}
h1 {
font-size: 28px;
margin-bottom: 20px;
color: #4CAF50;
}
.input-group {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
}
input[type="text"] {
width: calc(100% - 120px); /* 输入框宽度 */
padding: 15px;
margin-right: 10px; /* 与按钮的间距 */
border: 1px solid #ccc;
border-radius: 8px;
font-size: 18px;
transition: border-color 0.3s ease;
}
input[type="text"]:focus {
border-color: #4CAF50;
outline: none;
}
button {
padding: 12px 20px;
background-color: #4CAF50;
color: #fff;
border: none;
border-radius: 8px;
font-size: 18px;
cursor: pointer;
transition: background-color 0.3s ease;
}
button:hover {
background-color: #45a049;
}
ul {
list-style: none;
padding: 0;
margin: 0;
}
li {
display: flex;
justify-content: space-between;
align-items: center;
padding: 15px 0;
border-bottom: 1px solid #eee;
transition: background-color 0.3s ease;
}
li:hover {
background-color: #f9f9f9;
}
li:last-child {
border-bottom: none;
}
li button {
padding: 8px 12px;
background-color: #dc3545;
color: #fff;
border: none;
border-radius: 8px;
font-size: 16px;
cursor: pointer;
transition: background-color 0.3s ease;
}
li button:hover {
background-color: #a71d2a;
}
.todo-item {
flex: 1;
margin-right: 10px;
font-size: 18px;
}
.todo-item.completed {
text-decoration: line-through;
color: #ccc;
}
</style>
</head>
<body>
<div class="container">
<h1>我的待办清单 📝</h1>
<div class="input-group">
<input type="text" id="todoInput" placeholder="输入待办事项">
<button onclick="addTodo()">添加</button>
</div>
<ul id="todoList"></ul>
</div>
<script>
// 从本地加载数据
let todos = JSON.parse(localStorage.getItem('todos')) || [];
// 初始化显示
function init() {
const list = document.getElementById('todoList');
list.innerHTML = todos.map(todo => `
<li>
<span class="todo-item">${todo.text}</span>
<button onclick="deleteTodo(${todo.id})"><i class="fas fa-trash-alt"></i></button>
</li>
`).join('');
}
init();
// 添加待办
function addTodo() {
const input = document.getElementById('todoInput');
const text = input.value.trim();
if (!text) return;
const newTodo = {
id: Date.now(), // 用时间戳做唯一ID
text: text
};
todos.push(newTodo);
localStorage.setItem('todos', JSON.stringify(todos)); // 存本地
input.value = ''; // 清空输入框
init(); // 刷新列表
}
// 删除待办
function deleteTodo(id) {
todos = todos.filter(todo => todo.id !== id);
localStorage.setItem('todos', JSON.stringify(todos));
init();
}
</script>
</body>
</html>
3. 代码亮点
-
数据持久化:每次操作自动保存到 localStorage
-
防误触:空内容无法提交
-
极简 UI:纯原生实现,小白友好
下节预告
第 13 课:小白进阶必看!AJAX 与 Fetch 入门
-
什么是 API?如何获取服务器数据?
-
用 Fetch 实现天气查询小工具
-
常见网络错误处理
回复【JS】获取本课源码+工具包!