如何使用HTML5 localStorage API在浏览器中存储数据?

HTML5 localStorage将字符串数据保存在浏览器中,并且持续时间超出当前会话。localStorage存储数据,没有过期,而sessionStorage仅限于会话。关闭浏览器后,会话将丢失。

本地存储专为跨多个窗口且持续时间超出当前会话的存储而设计。特别是,出于性能方面的考虑,Web应用程序可能希望在客户端存储兆字节的用户数据,例如整个用户编写的文档或用户的邮箱。

您可以尝试运行以下代码来学习如何使用HTML5 localStorage

示例

<!DOCTYPE HTML>
<html>
   <body>
      <script type = "text/javascript">
         if( localStorage.hits ){
            localStorage.hits = Number(localStorage.hits) +1;
         }else{
            localStorage.hits = 1;
         }
         document.write("网站上的总点击数:" + localStorage.hits );
      </script>
      <p>Refresh the page to increase number of hits.</p>
      <p>Close the window and open it again and check the result.</p>
   </body>
</html>