第12课:小白进阶必看!客户端数据存储—让浏览器记住你的小秘密


青春因奋斗而闪光,梦想因拼搏而绽放!

你是否遇到过这样的尴尬:用户填了一半的表单,不小心刷新页面,所有内容都没了?别担心!今天我们就来学习如何让浏览器拥有“记忆”,即使用户关闭页面,数据也不会丢失!最后带大家做一个 「离线也能用的待办清单」,Let's go!

一、浏览器三大“储物柜”

1. localStorage:永久储物柜

特点: 关掉浏览器数据还在,除非手动删除

用法:

// 存数据(键值对形式)
localStorage.setItem('username''小明');

// 取数据
const name = localStorage.getItem('username');

// 删数据
localStorage.removeItem('username');

存对象(需用 JSON 转换):

const user = { id1age18 };
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. 功能演示

图片[1]-第12课:小白进阶必看!客户端数据存储—让浏览器记住你的小秘密-东升资源网

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;
            backgroundlinear-gradient(135deg, #74ebd5, #acb6e5);
            margin0;
            padding0;
            display: flex;
            justify-content: center;
            align-items: center;
            height100vh;
            color#333;
        }

        .container {
            background-color#fff;
            border-radius15px;
            box-shadow0 10px 20px rgba(0000.1);
            padding30px;
            width360px;
            text-align: center;
            transition: all 0.3s ease;
        }

        .container:hover {
            box-shadow0 15px 30px rgba(0000.2);
        }

        h1 {
            font-size28px;
            margin-bottom20px;
            color#4CAF50;
        }

        .input-group {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom20px;
        }

        input[type="text"] {
            widthcalc(100% - 120px); /* 输入框宽度 */
            padding15px;
            margin-right10px/* 与按钮的间距 */
            border1px solid #ccc;
            border-radius8px;
            font-size18px;
            transition: border-color 0.3s ease;
        }

        input[type="text"]:focus {
            border-color#4CAF50;
            outline: none;
        }

        button {
            padding12px 20px;
            background-color#4CAF50;
            color#fff;
            border: none;
            border-radius8px;
            font-size18px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        button:hover {
            background-color#45a049;
        }

        ul {
            list-style: none;
            padding0;
            margin0;
        }

        li {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding15px 0;
            border-bottom1px solid #eee;
            transition: background-color 0.3s ease;
        }

        li:hover {
            background-color#f9f9f9;
        }

        li:last-child {
            border-bottom: none;
        }

        li button {
            padding8px 12px;
            background-color#dc3545;
            color#fff;
            border: none;
            border-radius8px;
            font-size16px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        li button:hover {
            background-color#a71d2a;
        }

        .todo-item {
            flex1;
            margin-right10px;
            font-size18px;
        }

        .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 = {
                idDate.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:纯原生实现,小白友好

© 版权声明
THE END
分享
评论 抢沙发

请登录后发表评论

    暂无评论内容