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

เหตุการณ์ Storage ของ HTML DOM


เหตุการณ์ storage ของ HTML DOM จะเกิดขึ้นเมื่อมีการเปลี่ยนแปลงในพื้นที่จัดเก็บของหน้าต่าง เหตุการณ์ storage จะถูกทริกเกอร์ก็ต่อเมื่อหน้าต่างอื่นทำการเปลี่ยนแปลงพื้นที่จัดเก็บสำหรับหน้าต่างหนึ่ง เหตุการณ์นี้ไม่บับเบิ้ล (doesn't bubble) และสามารถยกเลิกได้ (cancellable)

ไวยากรณ์

ไวยากรณ์สำหรับ:

window.addEventListener("storage", SCRIPT);

ตัวอย่าง

มาดูตัวอย่างสำหรับเหตุการณ์ Storage:

<!DOCTYPE html> <html> <body> <h1>Storage Event Example</h1> <p>สร้างรายการ localStorage visits โดยคลิกปุ่มด้านล่าง</p> <button onclick="CreateVisits()">CREATE</button> <p id="Sample"></p> <script>    var y=1;    window.addEventListener("storage", DisplayChange);    function DisplayEvent(event) {       document.getElementById("Sample").innerHTML = "The number of visits has been updated";    }    function CreateVisits() {       y++;       var x=window.open("","WINDOW_1","width=350,height=350");       x.localStorage.setItem("VISITS",y);       setTimeout(function () { x.close();}, 4000);    } </script> </body> </html>

ผลลัพธ์

จะได้ผลลัพธ์ดังนี้:

เหตุการณ์ Storage ของ HTML DOM

เมื่อคลิกปุ่ม CHECK:

เหตุการณ์ Storage ของ HTML DOM

เมื่อพิมพ์ localstorage ในแท็บ console ในเครื่องมือผู้พัฒนา:

เหตุการณ์ Storage ของ HTML DOM