温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

HTML5如何实现离线存储

发布时间:2025-06-14 19:32:50 来源:亿速云 阅读:105 作者:小樊 栏目:编程语言

HTML5 提供了两种主要的离线存储机制:本地存储(LocalStorage)和IndexedDB。以下是这两种方法的简要介绍和使用示例:

1. 本地存储(LocalStorage)

LocalStorage 是一种简单的键值对存储方式,适合存储少量数据。它的数据在浏览器关闭后仍然保留。

使用示例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>LocalStorage Example</title>
</head>
<body>
    <h1>LocalStorage Example</h1>
    <input type="text" id="nameInput" placeholder="Enter your name">
    <button onclick="saveData()">Save</button>
    <button onclick="loadData()">Load</button>

    <script>
        function saveData() {
            const name = document.getElementById('nameInput').value;
            localStorage.setItem('userName', name);
            alert('Data saved!');
        }

        function loadData() {
            const name = localStorage.getItem('userName');
            if (name) {
                alert('Name: ' + name);
            } else {
                alert('No data found!');
            }
        }
    </script>
</body>
</html>

2. IndexedDB

IndexedDB 是一种更复杂的客户端存储解决方案,适合存储大量结构化数据。它提供了事务支持,并且可以存储二进制数据。

使用示例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>IndexedDB Example</title>
</head>
<body>
    <h1>IndexedDB Example</h1>
    <input type="text" id="nameInput" placeholder="Enter your name">
    <button onclick="saveData()">Save</button>
    <button onclick="loadData()">Load</button>

    <script>
        let db;

        function initDB() {
            const request = indexedDB.open('myDatabase', 1);

            request.onupgradeneeded = function(event) {
                db = event.target.result;
                const objectStore = db.createObjectStore('users', { keyPath: 'id', autoIncrement: true });
                objectStore.createIndex('name', 'name', { unique: false });
            };

            request.onsuccess = function(event) {
                db = event.target.result;
            };

            request.onerror = function(event) {
                console.error('Database error: ' + event.target.errorCode);
            };
        }

        function saveData() {
            const name = document.getElementById('nameInput').value;
            const transaction = db.transaction(['users'], 'readwrite');
            const objectStore = transaction.objectStore('users');
            const request = objectStore.add({ name: name });

            request.onsuccess = function(event) {
                alert('Data saved!');
            };

            request.onerror = function(event) {
                console.error('Error saving data: ' + event.target.errorCode);
            };
        }

        function loadData() {
            const transaction = db.transaction(['users'], 'readonly');
            const objectStore = transaction.objectStore('users');
            const request = objectStore.getAll();

            request.onsuccess = function(event) {
                const users = event.target.result;
                if (users.length > 0) {
                    alert('Name: ' + users[0].name);
                } else {
                    alert('No data found!');
                }
            };

            request.onerror = function(event) {
                console.error('Error loading data: ' + event.target.errorCode);
            };
        }

        initDB();
    </script>
</body>
</html>

总结

  • LocalStorage 适用于存储少量简单数据,如用户偏好设置。
  • IndexedDB 适用于存储大量结构化数据,支持事务和复杂查询。

选择哪种方法取决于你的具体需求。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI