Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> HTML

Các thuộc tính localStorage trong HTML DOM


Các thuộc tính localStorage trong HTML DOM cho phép người dùng lưu trữ các cặp khóa-giá trị trong chính trình duyệt để tham khảo sau này. Các cặp khóa-giá trị không bị mất cho đến khi bị xóa/xóa bỏ rõ ràng.

Cú pháp

Window.localStorage

Ở đây, localStorage có thể có các thuộc tính/phương thức sau:

  • setItem('key','value')
  • getItem('key')
  • removeItem('key')

Ví dụ

Ví dụ minh họa các thuộc tính localStorage:

<!DOCTYPE html> <html> <head> <title>LocalStorage clear()</title> <style>    form {       width:70%;       margin: 0 auto;       text-align: center;    }    * {       padding: 2px;       margin:5px;    }    input[type="button"] {       border-radius: 10px;    }    table,th,td {       border:1px solid black;       border-collapse: collapse;       margin: 0 auto;    } </style> </head> <body>    <form>       <fieldset>          <legend>LocalStorage clear( )</legend>          <table>             <tr>                <th>Khóa</th>                <th>Giá trị</th>             </tr>             <tr>                <td>PassKey</td>                <td>ja12ertplo</td>             </tr>          </table>          <input type="button" value="Lưu khóa" onclick="storeData()">          <input type="button" value="Xóa khóa" onclick="clearData()">          <div id="divDisplay"></div>       </fieldset>    </form>    <script>       var divDisplay = document.getElementById("divDisplay");       var extStyle = document.getElementById("extStyle");       function clearData(){          localStorage.clear();          divDisplay.textContent = 'Đã xóa thành công';       }       function storeData(){          localStorage.setItem('PassKey','ja12ertplo');          divDisplay.textContent = 'Đã lưu thành công';       }    </script> </body> </html>

Kết quả

Sau khi nhấn nút „Lưu khóa“:

Các thuộc tính localStorage trong HTML DOM

Sau khi nhấn nút „Xóa khóa“:

Các thuộc tính localStorage trong HTML DOM