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

เมธอด clear() ของ Local Storage ใน HTML DOM

เมธอด clear() ของ Local Storage ใช้สำหรับล้างข้อมูลทั้งหมดใน localStorage (หรือ sessionStorage)

ไวยากรณ์ (Syntax)

localStorage.clear()

หรือ

sessionStorage.clear()

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

ตัวอย่างด้านล่างเก็บและลบข้อมูลใน 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>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");
  
  function clearData() {
    localStorage.clear();
    divDisplay.textContent = 'Successfully Deleted';
  }
  
  function storeData() {
    localStorage.setItem('PassKey', 'ja12ertplo');
    divDisplay.textContent = 'Successfully Stored';
  }
</script>
</body>
</html>

ผลลัพธ์

หลังคลิก "Store Key": ข้อมูลถูกเก็บใน localStorage, แสดง "Successfully Stored"

หลังคลิก "Delete Key": ข้อมูลทั้งหมดใน localStorage ถูกลบ, แสดง "Successfully Deleted"

หมายเหตุ: รูปภาพตัวอย่างจากต้นฉบับไม่ได้รวมอยู่ในเนื้อหานี้