实际上,有两种方法可以通过JavaScript清除localStorage。
方式1-使用clear()
方法
localStorage.clear();
Way2-遍历localStorage并删除所有键
for(key in localStorage){ delete localStorage[key]; }
两种方式都可以。
<html> <body> <p id = "storage"></p> <script> if (typeof(Storage) !== "undefined") { localStorage.setItem("product", "Tutorix"); //显示前清除 localStorage.clear(); document.getElementById("storage").innerHTML = localStorage.getItem("product"); } else { document.getElementById("storage").innerHTML = "Sorry, no Web Storage compatibility..."; } </script> </body> </html>