Skip to content

9.1 本地存储API

关键词

本地存储、localStorage、sessionStorage、Web Storage、数据持久化、客户端存储、HTML5 API

学习目标

  • 理解HTML5本地存储API的概念和作用
  • 掌握localStorage和sessionStorage的区别和用法
  • 学会在HTML中声明和使用本地存储相关属性
  • 理解本地存储的安全性和限制
  • 能够创建支持本地存储的HTML应用结构

详细内容

9.1.1 本地存储API概述

什么是本地存储

HTML5本地存储API允许网页在用户的浏览器中存储数据,无需服务器参与:

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML5本地存储概述</title>
</head>
<body>
    <header>
        <h1>HTML5本地存储API</h1>
        <nav>
            <ul>
                <li><a href="#localStorage">localStorage</a></li>
                <li><a href="#sessionStorage">sessionStorage</a></li>
                <li><a href="#examples">实例演示</a></li>
            </ul>
        </nav>
    </header>
    
    <main>
        <section id="introduction">
            <h2>本地存储简介</h2>
            <article>
                <h3>存储类型对比</h3>
                <table>
                    <thead>
                        <tr>
                            <th>存储类型</th>
                            <th>生命周期</th>
                            <th>存储大小</th>
                            <th>作用域</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>localStorage</td>
                            <td>持久存储</td>
                            <td>5-10MB</td>
                            <td>同源策略</td>
                        </tr>
                        <tr>
                            <td>sessionStorage</td>
                            <td>会话期间</td>
                            <td>5-10MB</td>
                            <td>当前标签页</td>
                        </tr>
                        <tr>
                            <td>Cookie</td>
                            <td>可设置过期时间</td>
                            <td>4KB</td>
                            <td>同源策略</td>
                        </tr>
                    </tbody>
                </table>
            </article>
        </section>
        
        <section id="localStorage">
            <h2>localStorage本地存储</h2>
            <article>
                <h3>基本结构</h3>
                <p>localStorage用于长期存储数据,数据在浏览器关闭后仍然保留:</p>
                
                <div class="storage-demo">
                    <h4>用户偏好设置</h4>
                    <form id="preferences-form">
                        <fieldset>
                            <legend>个人设置</legend>
                            
                            <label for="username">用户名:</label>
                            <input type="text" id="username" name="username" 
                                   placeholder="请输入用户名" data-storage="localStorage">
                            
                            <label for="theme">主题:</label>
                            <select id="theme" name="theme" data-storage="localStorage">
                                <option value="light">浅色主题</option>
                                <option value="dark">深色主题</option>
                                <option value="auto">自动</option>
                            </select>
                            
                            <label for="language">语言:</label>
                            <select id="language" name="language" data-storage="localStorage">
                                <option value="zh-CN">中文</option>
                                <option value="en">English</option>
                                <option value="ja">日本語</option>
                            </select>
                            
                            <label for="font-size">字体大小:</label>
                            <input type="range" id="font-size" name="font-size" 
                                   min="12" max="24" value="16" data-storage="localStorage">
                            <span id="font-size-value">16px</span>
                        </fieldset>
                        
                        <button type="button" onclick="savePreferences()">保存设置</button>
                        <button type="button" onclick="loadPreferences()">加载设置</button>
                        <button type="button" onclick="clearPreferences()">清除设置</button>
                    </form>
                </div>
            </article>
        </section>
        
        <section id="sessionStorage">
            <h2>sessionStorage会话存储</h2>
            <article>
                <h3>表单数据临时保存</h3>
                <p>sessionStorage用于临时存储数据,浏览器标签页关闭后数据会被清除:</p>
                
                <div class="storage-demo">
                    <h4>文章草稿</h4>
                    <form id="article-form">
                        <fieldset>
                            <legend>文章编辑</legend>
                            
                            <label for="article-title">标题:</label>
                            <input type="text" id="article-title" name="title" 
                                   placeholder="请输入文章标题" data-storage="sessionStorage">
                            
                            <label for="article-category">分类:</label>
                            <select id="article-category" name="category" data-storage="sessionStorage">
                                <option value="">请选择分类</option>
                                <option value="tech">技术</option>
                                <option value="life">生活</option>
                                <option value="travel">旅行</option>
                            </select>
                            
                            <label for="article-content">内容:</label>
                            <textarea id="article-content" name="content" 
                                      rows="10" cols="50" 
                                      placeholder="请输入文章内容" 
                                      data-storage="sessionStorage"></textarea>
                            
                            <label for="article-tags">标签:</label>
                            <input type="text" id="article-tags" name="tags" 
                                   placeholder="请输入标签,用逗号分隔" data-storage="sessionStorage">
                        </fieldset>
                        
                        <button type="button" onclick="saveDraft()">保存草稿</button>
                        <button type="button" onclick="loadDraft()">加载草稿</button>
                        <button type="button" onclick="clearDraft()">清除草稿</button>
                    </form>
                </div>
            </article>
        </section>
        
        <section id="examples">
            <h2>实际应用示例</h2>
            
            <article>
                <h3>购物车数据存储</h3>
                <div class="storage-demo">
                    <h4>在线商店购物车</h4>
                    <div class="product-list">
                        <div class="product" data-id="1">
                            <h5>产品A</h5>
                            <p>价格:¥99.00</p>
                            <button type="button" onclick="addToCart(1, '产品A', 99.00)">
                                加入购物车
                            </button>
                        </div>
                        
                        <div class="product" data-id="2">
                            <h5>产品B</h5>
                            <p>价格:¥199.00</p>
                            <button type="button" onclick="addToCart(2, '产品B', 199.00)">
                                加入购物车
                            </button>
                        </div>
                        
                        <div class="product" data-id="3">
                            <h5>产品C</h5>
                            <p>价格:¥299.00</p>
                            <button type="button" onclick="addToCart(3, '产品C', 299.00)">
                                加入购物车
                            </button>
                        </div>
                    </div>
                    
                    <div class="cart">
                        <h4>购物车</h4>
                        <div id="cart-items" data-storage="localStorage">
                            <!-- 购物车商品将在这里显示 -->
                        </div>
                        <div class="cart-actions">
                            <button type="button" onclick="loadCart()">刷新购物车</button>
                            <button type="button" onclick="clearCart()">清空购物车</button>
                        </div>
                    </div>
                </div>
            </article>
            
            <article>
                <h3>用户浏览历史</h3>
                <div class="storage-demo">
                    <h4>文章浏览记录</h4>
                    <div class="article-list">
                        <article class="article-item" data-id="1">
                            <h5><a href="#" onclick="readArticle(1, 'HTML5基础教程')">HTML5基础教程</a></h5>
                            <p>发布时间:2024-01-01</p>
                            <p>简介:学习HTML5的基础知识和核心概念...</p>
                        </article>
                        
                        <article class="article-item" data-id="2">
                            <h5><a href="#" onclick="readArticle(2, 'CSS3动画详解')">CSS3动画详解</a></h5>
                            <p>发布时间:2024-01-02</p>
                            <p>简介:深入了解CSS3动画的实现方法...</p>
                        </article>
                        
                        <article class="article-item" data-id="3">
                            <h5><a href="#" onclick="readArticle(3, 'JavaScript进阶')">JavaScript进阶</a></h5>
                            <p>发布时间:2024-01-03</p>
                            <p>简介:掌握JavaScript的高级特性和最佳实践...</p>
                        </article>
                    </div>
                    
                    <div class="reading-history">
                        <h4>浏览历史</h4>
                        <div id="history-list" data-storage="sessionStorage">
                            <!-- 浏览历史将在这里显示 -->
                        </div>
                        <div class="history-actions">
                            <button type="button" onclick="loadHistory()">刷新历史</button>
                            <button type="button" onclick="clearHistory()">清除历史</button>
                        </div>
                    </div>
                </div>
            </article>
        </section>
        
        <section id="advanced">
            <h2>高级应用场景</h2>
            
            <article>
                <h3>多标签页数据同步</h3>
                <div class="storage-demo">
                    <h4>实时消息通知</h4>
                    <div class="notification-system">
                        <div class="notification-panel">
                            <h5>消息面板</h5>
                            <div id="notification-list" data-storage="localStorage">
                                <!-- 通知消息将在这里显示 -->
                            </div>
                        </div>
                        
                        <div class="notification-controls">
                            <input type="text" id="new-message" placeholder="输入新消息">
                            <button type="button" onclick="addNotification()">发送消息</button>
                            <button type="button" onclick="loadNotifications()">刷新消息</button>
                        </div>
                    </div>
                </div>
            </article>
            
            <article>
                <h3>应用状态保存</h3>
                <div class="storage-demo">
                    <h4>游戏进度保存</h4>
                    <div class="game-state">
                        <div class="game-info">
                            <h5>游戏信息</h5>
                            <p>当前等级:<span id="game-level" data-storage="localStorage">1</span></p>
                            <p>经验值:<span id="game-exp" data-storage="localStorage">0</span></p>
                            <p>金币:<span id="game-coins" data-storage="localStorage">100</span></p>
                            <p>游戏时间:<span id="game-time" data-storage="localStorage">00:00:00</span></p>
                        </div>
                        
                        <div class="game-controls">
                            <button type="button" onclick="saveGameState()">保存游戏</button>
                            <button type="button" onclick="loadGameState()">加载游戏</button>
                            <button type="button" onclick="resetGameState()">重置游戏</button>
                        </div>
                    </div>
                </div>
            </article>
        </section>
    </main>
    
    <aside>
        <h2>本地存储最佳实践</h2>
        <ul>
            <li><strong>数据结构化</strong>:使用JSON格式存储复杂数据</li>
            <li><strong>异常处理</strong>:考虑存储空间不足的情况</li>
            <li><strong>数据验证</strong>:在读取数据时进行有效性检查</li>
            <li><strong>隐私保护</strong>:不存储敏感信息</li>
            <li><strong>性能优化</strong>:避免频繁的读写操作</li>
        </ul>
    </aside>
    
    <footer>
        <p>&copy; 2024 HTML5本地存储API学习文档</p>
    </footer>
    
    <!-- 模拟的JavaScript功能说明 -->
    <script type="text/plain">
        // 注意:这里只是展示HTML结构,实际的JavaScript功能需要单独实现
        
        // localStorage示例函数
        function savePreferences() {
            // 保存用户偏好设置到localStorage
        }
        
        function loadPreferences() {
            // 从localStorage加载用户偏好设置
        }
        
        function clearPreferences() {
            // 清除localStorage中的用户偏好设置
        }
        
        // sessionStorage示例函数
        function saveDraft() {
            // 保存文章草稿到sessionStorage
        }
        
        function loadDraft() {
            // 从sessionStorage加载文章草稿
        }
        
        function clearDraft() {
            // 清除sessionStorage中的文章草稿
        }
        
        // 购物车功能
        function addToCart(id, name, price) {
            // 添加商品到购物车
        }
        
        function loadCart() {
            // 加载购物车数据
        }
        
        function clearCart() {
            // 清空购物车
        }
        
        // 浏览历史功能
        function readArticle(id, title) {
            // 记录文章阅读历史
        }
        
        function loadHistory() {
            // 加载浏览历史
        }
        
        function clearHistory() {
            // 清除浏览历史
        }
    </script>
</body>
</html>

9.1.2 localStorage详细应用

持久化数据存储

localStorage用于长期存储用户数据:

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>localStorage详细应用</title>
</head>
<body>
    <header>
        <h1>localStorage持久化存储</h1>
        <p>数据在浏览器关闭后仍然保留</p>
    </header>
    
    <main>
        <section class="storage-demo">
            <h2>用户配置管理</h2>
            <form id="user-config-form">
                <fieldset>
                    <legend>界面设置</legend>
                    
                    <div class="form-group">
                        <label for="site-theme">网站主题:</label>
                        <select id="site-theme" name="theme" data-storage="localStorage" data-key="userTheme">
                            <option value="default">默认主题</option>
                            <option value="dark">深色主题</option>
                            <option value="light">浅色主题</option>
                            <option value="colorful">彩色主题</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="layout-mode">布局模式:</label>
                        <select id="layout-mode" name="layout" data-storage="localStorage" data-key="layoutMode">
                            <option value="fixed">固定布局</option>
                            <option value="fluid">流式布局</option>
                            <option value="responsive">响应式布局</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="sidebar-position">侧边栏位置:</label>
                        <select id="sidebar-position" name="sidebar" data-storage="localStorage" data-key="sidebarPosition">
                            <option value="left">左侧</option>
                            <option value="right">右侧</option>
                            <option value="hidden">隐藏</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="content-width">内容宽度:</label>
                        <input type="range" id="content-width" name="width" 
                               min="800" max="1400" step="100" value="1200"
                               data-storage="localStorage" data-key="contentWidth">
                        <span id="width-display">1200px</span>
                    </div>
                    
                    <div class="form-group">
                        <label for="auto-save">自动保存:</label>
                        <input type="checkbox" id="auto-save" name="autoSave" 
                               data-storage="localStorage" data-key="autoSave">
                        <span>启用自动保存功能</span>
                    </div>
                </fieldset>
                
                <fieldset>
                    <legend>个人信息</legend>
                    
                    <div class="form-group">
                        <label for="display-name">显示名称:</label>
                        <input type="text" id="display-name" name="displayName" 
                               placeholder="请输入显示名称"
                               data-storage="localStorage" data-key="displayName">
                    </div>
                    
                    <div class="form-group">
                        <label for="user-email">邮箱地址:</label>
                        <input type="email" id="user-email" name="email" 
                               placeholder="请输入邮箱地址"
                               data-storage="localStorage" data-key="userEmail">
                    </div>
                    
                    <div class="form-group">
                        <label for="user-location">所在地:</label>
                        <input type="text" id="user-location" name="location" 
                               placeholder="请输入所在地"
                               data-storage="localStorage" data-key="userLocation">
                    </div>
                    
                    <div class="form-group">
                        <label for="user-bio">个人简介:</label>
                        <textarea id="user-bio" name="bio" rows="4" 
                                  placeholder="请输入个人简介"
                                  data-storage="localStorage" data-key="userBio"></textarea>
                    </div>
                </fieldset>
                
                <div class="form-actions">
                    <button type="button" onclick="saveToLocalStorage()">保存配置</button>
                    <button type="button" onclick="loadFromLocalStorage()">加载配置</button>
                    <button type="button" onclick="resetLocalStorage()">重置配置</button>
                    <button type="button" onclick="exportLocalStorage()">导出配置</button>
                </div>
            </form>
        </section>
        
        <section class="storage-demo">
            <h2>应用数据管理</h2>
            <div class="data-manager">
                <div class="data-section">
                    <h3>待办事项列表</h3>
                    <div class="todo-container">
                        <div class="todo-input">
                            <input type="text" id="new-todo" placeholder="添加新的待办事项">
                            <button type="button" onclick="addTodo()">添加</button>
                        </div>
                        
                        <div class="todo-list" id="todo-list" data-storage="localStorage" data-key="todoList">
                            <!-- 待办事项将在这里显示 -->
                        </div>
                        
                        <div class="todo-actions">
                            <button type="button" onclick="loadTodos()">刷新列表</button>
                            <button type="button" onclick="clearTodos()">清空列表</button>
                        </div>
                    </div>
                </div>
                
                <div class="data-section">
                    <h3>书签管理</h3>
                    <div class="bookmark-container">
                        <div class="bookmark-input">
                            <input type="text" id="bookmark-title" placeholder="书签标题">
                            <input type="url" id="bookmark-url" placeholder="书签链接">
                            <button type="button" onclick="addBookmark()">添加书签</button>
                        </div>
                        
                        <div class="bookmark-list" id="bookmark-list" data-storage="localStorage" data-key="bookmarks">
                            <!-- 书签将在这里显示 -->
                        </div>
                        
                        <div class="bookmark-actions">
                            <button type="button" onclick="loadBookmarks()">刷新书签</button>
                            <button type="button" onclick="clearBookmarks()">清空书签</button>
                        </div>
                    </div>
                </div>
            </div>
        </section>
        
        <section class="storage-demo">
            <h2>数据统计和分析</h2>
            <div class="stats-container">
                <div class="stats-display">
                    <h3>存储使用情况</h3>
                    <div class="stats-grid">
                        <div class="stat-item">
                            <h4>已用空间</h4>
                            <p id="used-space" data-storage="localStorage">计算中...</p>
                        </div>
                        
                        <div class="stat-item">
                            <h4>存储项目数</h4>
                            <p id="storage-items" data-storage="localStorage">计算中...</p>
                        </div>
                        
                        <div class="stat-item">
                            <h4>最后更新</h4>
                            <p id="last-update" data-storage="localStorage">未知</p>
                        </div>
                    </div>
                </div>
                
                <div class="stats-actions">
                    <button type="button" onclick="calculateStats()">计算统计</button>
                    <button type="button" onclick="exportAllData()">导出所有数据</button>
                    <button type="button" onclick="clearAllData()">清除所有数据</button>
                </div>
            </div>
        </section>
    </main>
    
    <aside>
        <h2>localStorage特性</h2>
        <dl>
            <dt>存储大小</dt>
            <dd>通常为5-10MB,根据浏览器和设备而定</dd>
            
            <dt>数据类型</dt>
            <dd>只能存储字符串,复杂数据需要JSON序列化</dd>
            
            <dt>生命周期</dt>
            <dd>数据永久保存,直到被明确删除</dd>
            
            <dt>作用域</dt>
            <dd>同源策略限制,相同协议、域名、端口的页面共享</dd>
            
            <dt>性能</dt>
            <dd>同步API,大量数据操作可能阻塞UI线程</dd>
        </dl>
    </aside>
    
    <footer>
        <p><small>注意:本示例仅展示HTML结构,实际功能需要JavaScript实现</small></p>
    </footer>
</body>
</html>

9.1.3 sessionStorage详细应用

会话级数据存储

sessionStorage用于临时存储会话数据:

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>sessionStorage详细应用</title>
</head>
<body>
    <header>
        <h1>sessionStorage会话存储</h1>
        <p>数据仅在当前标签页会话中有效</p>
    </header>
    
    <main>
        <section class="storage-demo">
            <h2>表单数据临时保存</h2>
            <form id="contact-form">
                <fieldset>
                    <legend>联系信息</legend>
                    
                    <div class="form-group">
                        <label for="contact-name">姓名:</label>
                        <input type="text" id="contact-name" name="name" 
                               placeholder="请输入您的姓名"
                               data-storage="sessionStorage" data-key="contactName">
                    </div>
                    
                    <div class="form-group">
                        <label for="contact-phone">电话:</label>
                        <input type="tel" id="contact-phone" name="phone" 
                               placeholder="请输入您的电话号码"
                               data-storage="sessionStorage" data-key="contactPhone">
                    </div>
                    
                    <div class="form-group">
                        <label for="contact-email">邮箱:</label>
                        <input type="email" id="contact-email" name="email" 
                               placeholder="请输入您的邮箱地址"
                               data-storage="sessionStorage" data-key="contactEmail">
                    </div>
                    
                    <div class="form-group">
                        <label for="contact-company">公司:</label>
                        <input type="text" id="contact-company" name="company" 
                               placeholder="请输入您的公司名称"
                               data-storage="sessionStorage" data-key="contactCompany">
                    </div>
                    
                    <div class="form-group">
                        <label for="contact-subject">主题:</label>
                        <select id="contact-subject" name="subject" 
                                data-storage="sessionStorage" data-key="contactSubject">
                            <option value="">请选择主题</option>
                            <option value="inquiry">咨询</option>
                            <option value="support">技术支持</option>
                            <option value="feedback">意见反馈</option>
                            <option value="partnership">合作</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="contact-message">消息:</label>
                        <textarea id="contact-message" name="message" rows="6" 
                                  placeholder="请输入您的消息内容"
                                  data-storage="sessionStorage" data-key="contactMessage"></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label for="contact-priority">优先级:</label>
                        <input type="range" id="contact-priority" name="priority" 
                               min="1" max="5" value="3"
                               data-storage="sessionStorage" data-key="contactPriority">
                        <span id="priority-display">中等</span>
                    </div>
                    
                    <div class="form-group">
                        <label>
                            <input type="checkbox" id="contact-newsletter" name="newsletter" 
                                   data-storage="sessionStorage" data-key="contactNewsletter">
                            订阅我们的新闻通讯
                        </label>
                    </div>
                </fieldset>
                
                <div class="form-actions">
                    <button type="button" onclick="saveFormData()">保存草稿</button>
                    <button type="button" onclick="loadFormData()">加载草稿</button>
                    <button type="button" onclick="clearFormData()">清除草稿</button>
                    <button type="submit">提交表单</button>
                </div>
            </form>
        </section>
        
        <section class="storage-demo">
            <h2>购物流程数据</h2>
            <div class="shopping-process">
                <div class="process-steps">
                    <h3>购物步骤</h3>
                    <ol>
                        <li><a href="#step1" onclick="showStep(1)">选择商品</a></li>
                        <li><a href="#step2" onclick="showStep(2)">确认订单</a></li>
                        <li><a href="#step3" onclick="showStep(3)">支付方式</a></li>
                        <li><a href="#step4" onclick="showStep(4)">配送信息</a></li>
                        <li><a href="#step5" onclick="showStep(5)">完成订单</a></li>
                    </ol>
                </div>
                
                <div class="step-content" id="step1" data-storage="sessionStorage" data-key="shoppingStep1">
                    <h3>步骤1:选择商品</h3>
                    <div class="product-selection">
                        <div class="product-item">
                            <h4>商品A</h4>
                            <p>价格:¥299.00</p>
                            <label for="quantity-a">数量:</label>
                            <input type="number" id="quantity-a" min="0" max="10" value="0"
                                   data-storage="sessionStorage" data-key="quantityA">
                        </div>
                        
                        <div class="product-item">
                            <h4>商品B</h4>
                            <p>价格:¥399.00</p>
                            <label for="quantity-b">数量:</label>
                            <input type="number" id="quantity-b" min="0" max="10" value="0"
                                   data-storage="sessionStorage" data-key="quantityB">
                        </div>
                        
                        <div class="product-item">
                            <h4>商品C</h4>
                            <p>价格:¥499.00</p>
                            <label for="quantity-c">数量:</label>
                            <input type="number" id="quantity-c" min="0" max="10" value="0"
                                   data-storage="sessionStorage" data-key="quantityC">
                        </div>
                    </div>
                </div>
                
                <div class="step-content" id="step2" data-storage="sessionStorage" data-key="shoppingStep2">
                    <h3>步骤2:确认订单</h3>
                    <div class="order-summary">
                        <h4>订单摘要</h4>
                        <div id="order-items" data-storage="sessionStorage">
                            <!-- 订单项目将在这里显示 -->
                        </div>
                        
                        <div class="order-options">
                            <label for="coupon-code">优惠码:</label>
                            <input type="text" id="coupon-code" placeholder="请输入优惠码"
                                   data-storage="sessionStorage" data-key="couponCode">
                            
                            <label for="special-instructions">特殊说明:</label>
                            <textarea id="special-instructions" rows="3" 
                                      placeholder="请输入特殊说明"
                                      data-storage="sessionStorage" data-key="specialInstructions"></textarea>
                        </div>
                    </div>
                </div>
                
                <div class="step-content" id="step3" data-storage="sessionStorage" data-key="shoppingStep3">
                    <h3>步骤3:支付方式</h3>
                    <div class="payment-methods">
                        <fieldset>
                            <legend>选择支付方式</legend>
                            
                            <label>
                                <input type="radio" name="payment" value="credit" 
                                       data-storage="sessionStorage" data-key="paymentMethod">
                                信用卡支付
                            </label>
                            
                            <label>
                                <input type="radio" name="payment" value="debit" 
                                       data-storage="sessionStorage" data-key="paymentMethod">
                                借记卡支付
                            </label>
                            
                            <label>
                                <input type="radio" name="payment" value="paypal" 
                                       data-storage="sessionStorage" data-key="paymentMethod">
                                PayPal支付
                            </label>
                            
                            <label>
                                <input type="radio" name="payment" value="alipay" 
                                       data-storage="sessionStorage" data-key="paymentMethod">
                                支付宝支付
                            </label>
                        </fieldset>
                    </div>
                </div>
                
                <div class="step-content" id="step4" data-storage="sessionStorage" data-key="shoppingStep4">
                    <h3>步骤4:配送信息</h3>
                    <div class="delivery-info">
                        <div class="form-group">
                            <label for="delivery-address">配送地址:</label>
                            <textarea id="delivery-address" rows="3" 
                                      placeholder="请输入详细的配送地址"
                                      data-storage="sessionStorage" data-key="deliveryAddress"></textarea>
                        </div>
                        
                        <div class="form-group">
                            <label for="delivery-date">期望配送日期:</label>
                            <input type="date" id="delivery-date"
                                   data-storage="sessionStorage" data-key="deliveryDate">
                        </div>
                        
                        <div class="form-group">
                            <label for="delivery-time">期望配送时间:</label>
                            <select id="delivery-time"
                                    data-storage="sessionStorage" data-key="deliveryTime">
                                <option value="">请选择时间段</option>
                                <option value="morning">上午 9:00-12:00</option>
                                <option value="afternoon">下午 13:00-17:00</option>
                                <option value="evening">晚上 18:00-21:00</option>
                            </select>
                        </div>
                    </div>
                </div>
                
                <div class="step-content" id="step5" data-storage="sessionStorage" data-key="shoppingStep5">
                    <h3>步骤5:完成订单</h3>
                    <div class="order-confirmation">
                        <h4>订单确认</h4>
                        <div id="final-order-summary" data-storage="sessionStorage">
                            <!-- 最终订单摘要将在这里显示 -->
                        </div>
                        
                        <div class="confirmation-actions">
                            <button type="button" onclick="confirmOrder()">确认订单</button>
                            <button type="button" onclick="cancelOrder()">取消订单</button>
                        </div>
                    </div>
                </div>
                
                <div class="process-actions">
                    <button type="button" onclick="saveShoppingData()">保存进度</button>
                    <button type="button" onclick="loadShoppingData()">加载进度</button>
                    <button type="button" onclick="clearShoppingData()">清除进度</button>
                </div>
            </div>
        </section>
        
        <section class="storage-demo">
            <h2>临时计算器</h2>
            <div class="calculator">
                <div class="calc-display">
                    <input type="text" id="calc-display" readonly 
                           data-storage="sessionStorage" data-key="calcDisplay">
                </div>
                
                <div class="calc-history">
                    <h4>计算历史</h4>
                    <div id="calc-history-list" data-storage="sessionStorage" data-key="calcHistory">
                        <!-- 计算历史将在这里显示 -->
                    </div>
                </div>
                
                <div class="calc-buttons">
                    <button type="button" onclick="calcClear()">清除</button>
                    <button type="button" onclick="calcClearHistory()">清除历史</button>
                    <button type="button" onclick="saveCalcSession()">保存会话</button>
                    <button type="button" onclick="loadCalcSession()">加载会话</button>
                </div>
            </div>
        </section>
    </main>
    
    <aside>
        <h2>sessionStorage特性</h2>
        <dl>
            <dt>生命周期</dt>
            <dd>仅在当前标签页会话中有效,关闭标签页后数据消失</dd>
            
            <dt>作用域</dt>
            <dd>限制在当前标签页,不同标签页的sessionStorage相互独立</dd>
            
            <dt>存储大小</dt>
            <dd>通常为5-10MB,与localStorage相同</dd>
            
            <dt>数据类型</dt>
            <dd>只能存储字符串,复杂数据需要JSON序列化</dd>
            
            <dt>适用场景</dt>
            <dd>表单草稿、购物流程、临时计算、会话状态等</dd>
        </dl>
    </aside>
    
    <footer>
        <p><small>注意:本示例仅展示HTML结构,实际功能需要JavaScript实现</small></p>
    </footer>
</body>
</html>

关键要点总结

  1. localStorage:用于长期存储数据,浏览器关闭后数据仍然保留
  2. sessionStorage:用于临时存储数据,标签页关闭后数据消失
  3. 数据格式:只能存储字符串,复杂数据需要JSON序列化
  4. 存储限制:通常为5-10MB,受浏览器和设备限制
  5. 安全性:遵循同源策略,不存储敏感信息

参考资源

常见问题解答

Q: localStorage和sessionStorage有什么区别? A: localStorage数据持久保存直到被删除,sessionStorage数据仅在当前标签页会话中有效。

Q: 如何检测浏览器是否支持本地存储? A: 可以通过检测typeof(Storage) !== "undefined"来判断浏览器支持情况。

Q: 存储空间不足时会发生什么? A: 浏览器会抛出异常,需要在代码中进行异常处理。

Q: 如何实现不同标签页之间的数据同步? A: 使用localStorage结合storage事件可以实现跨标签页数据同步。

Q: 本地存储的数据是否安全? A: 本地存储的数据可能被用户或其他程序访问,不应存储敏感信息如密码等。