Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> HTML

คุณสมบัติ localStorage ใน HTML DOM

คุณสมบัติ localStorage ของ HTML DOM ช่วยให้ผู้ใช้จัดเก็บคู่คีย์-ค่า (key-value pairs) ไว้ในเบราว์เซอร์ท้องถิ่นเพื่อการอ้างอิงในอนาคต คู่คีย์-ค่าจะไม่หายไปจนกว่าจะถูกลบ/ล้างออกอย่างชัดเจน

ไวยากรณ์ (Syntax)

Window.localStorage

ที่นี่ localStorage สามารถมีคุณสมบัติ/เมธอดต่อไปนี้:

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

ตัวอย่างการใช้งาน

ตัวอย่างต่อไปนี้แสดงการใช้งาน localStorage properties:

<!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>Key</th>                <th>Value</th>             </tr>             <tr>                <td>PassKey</td>                <td>ja12ertplo</td>               </tr>          </table>          <input type="button" value="Store Key" onclick="storeData()">          <input type="button" value="Delete Key" 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 = 'Succesfully Deleted';       }       function storeData(){          localStorage.setItem('PassKey','ja12ertplo');          divDisplay.textContent = 'Succesfully Stored';       }    </script> </body> </html>

ผลลัพธ์

หลังคลิกปุ่ม 'Store Key':

คุณสมบัติ localStorage ใน HTML DOM

หลังคลิกปุ่ม 'Delete Key':

คุณสมบัติ localStorage ใน HTML DOM