HTML5 - Web 存储

HTML5 - Web 存储 首页 / HTML5入门教程 / HTML5 - Web 存储

HTML5引入了两种机制是会话存储(Session Storage)和本地存储(Local Storage),它们将用于处理不同的情况。

几乎每个浏览器的最新版本都支持HTML5存储,包括Internet Explorer。

Session Storage

HTML5引入了 sessionStorage 属性,站点将使用该属性将数据添加到会话存储中,并且在该窗口中打开的同一站点中的任何页面(即 session)都可以访问它,一旦您关闭窗口,会话就会丢失,以下是设置会话变量并访问该变量的代码-

<!DOCTYPE HTML>

<html>
   <body>
      <script type="text/javascript">
         
         if( sessionStorage.hits ) {
            sessionStorage.hits=Number(sessionStorage.hits) +1;
         } else {
            sessionStorage.hits=1;
         }
         document.write("Total Hits :" + sessionStorage.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>

这将产生以下输出-

链接:https://www.learnfk.comhttps://www.learnfk.com/html5/html5-web-storage.html

来源:LearnFk无涯教程网

Local Storage

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("Total Hits :" + 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>

这将产生以下输出-

链接:https://www.learnfk.comhttps://www.learnfk.com/html5/html5-web-storage.html

来源:LearnFk无涯教程网

Delete Web Storage

要清除本地存储设置,您需要调用 localStorage.remove('key')其中"key"是您要删除的值的键。如果要清除所有设置,则需要调用 localStorage.clear()方法。

以下代码将清除完整的本地存储-

<!DOCTYPE HTML>

<html>
   <body>

      <script type="text/javascript">
         localStorage.clear();

         //Reset number of hits.
         if( localStorage.hits ) {
            localStorage.hits=Number(localStorage.hits) +1;
         } else {
            localStorage.hits=1;
         }
         document.write("Total Hits :" + localStorage.hits );
			
      </script>
		
      <p>Refreshing the page would not to increase hit counter.</p>
      <p>Close the window and open it again and check the result.</p>

   </body>
</html>

这将产生以下输出-

链接:https://www.learnfk.comhttps://www.learnfk.com/html5/html5-web-storage.html

来源:LearnFk无涯教程网

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

赵成的运维体系管理课 -〔赵成〕

微服务架构实战160讲 -〔杨波〕

算法面试通关40讲 -〔覃超〕

大规模数据处理实战 -〔蔡元楠〕

Python核心技术与实战 -〔景霄〕

Spring编程常见错误50例 -〔傅健〕

深入C语言和程序运行原理 -〔于航〕

Serverless进阶实战课 -〔静远〕

给程序员的写作课 -〔高磊〕

好记忆不如烂笔头。留下您的足迹吧 :)