如何使用 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("Total Hits on the website:" + 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>

更新於: 2020 年 2 月 25 日

204 次瀏覽

開啟你的 職業生涯

透過完成該課程獲得認證

開始
廣告
© . All rights reserved.