无涯教程-HTML5 - Web 存储

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

几乎每个浏览器的最新版本都支持HTML5存储,包括Inter*** 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>

这将产生以下输出-

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>

这将产生以下输出-

HTML5 - Web 存储 - 无涯教程网无涯教程网提供HTML5引入了两种机制是会话存储(Session Storage)和本地存储(Local Storage),它们将...https://www.learnfk.***/html5/html5-web-storage.html

转载请说明出处内容投诉
CSS教程_站长资源网 » 无涯教程-HTML5 - Web 存储

发表评论

欢迎 访客 发表评论

一个令你着迷的主题!

查看演示 官网购买