HTML5 - Web 存储

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

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

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

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

来源:LearnFk无涯教程网

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>

这将产生以下输出-

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>

这将产生以下输出-

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>

这将产生以下输出-

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

技术教程推荐

AI技术内参 -〔洪亮劼〕

深入浅出gRPC -〔李林锋〕

Java性能调优实战 -〔刘超〕

OpenResty从入门到实战 -〔温铭〕

玩转webpack -〔程柳锋〕

Serverless入门课 -〔蒲松洋(秦粤)〕

软件设计之美 -〔郑晔〕

Redis核心技术与实战 -〔蒋德钧〕

Go进阶 · 分布式爬虫实战 -〔郑建勋〕

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