JQuery和JS操作LocalStorage/SessionStorage的方法

來源:互聯網
上載者:User

標籤:log   charset   func   url   target   jquery操作   tail   資料存放區   on()   

出處:http://blog.csdn.net/djzhao627/article/details/50747628

首先說一下LocalStorage和SessionStorageLocalStorage
  • 是對Cookie的最佳化
  • 沒有時間限制的資料存放區
  • 在隱私模式下不可讀取
  • 大小限制在500萬字元左右,各個瀏覽器不一致
  • 在所有同源視窗中都是共用的
  • 本質是在讀寫檔案,資料多的話會比較卡(firefox會一次性將資料匯入記憶體)
  • 不能被爬蟲爬取,不要用它完全取代URL傳參
  • IE7及以下不支援外,其他標準瀏覽器都完全支援
SessionStorage
  • 針對一個 session 的資料存放區
  • 大小限制在5M左右,各個瀏覽器不一致
  • 僅在當前瀏覽器視窗關閉前有效(適合會話驗證)
  • 不在不同的瀏覽器視窗中共用,即使是同一個頁面
JS下的操作方法
  • 擷取索引值:localStorage.getItem(“key”)
  • 設定索引值:localStorage.setItem(“key”,”value”)
  • 清除索引值:localStorage.removeItem(“key”)
  • 清除所有索引值:localStorage.clear()
  • 擷取索引值2:localStorage.keyName
  • 設定索引值2:localStorage.keyName = “value”
JQ下的操作方法(JS方法前加”window.”)
  • 擷取索引值:window.localStorage.getItem(“key”)
  • 設定索引值:window.localStorage.setItem(“key”,”value”)
  • 清除索引值:window.localStorage.removeItem(“key”)
  • 清除所有索引值:window.localStorage.clear()
  • 擷取索引值2:window.localStorage.keyName
  • 設定索引值2:window.localStorage.keyName = “value”
樣本
<!DOCTYPE html><html><head lang="en">    <meta charset="UTF-8">    <title></title>    <script type="text/javascript" charset="utf-8" src="js/jquery.min.js"></script>    <script type="text/javascript">        // JS操作部分        localStorage.JSa="JSA";        document.write(localStorage.JSa);        localStorage.setItem(‘JSb‘,‘&nbsp;JSB‘);        document.write(localStorage.getItem(‘JSb‘));        // JQuery操作部分        $(function(){            window.localStorage.JQa="JQA";            $("#a").text(window.localStorage.JQa);            window.localStorage.setItem(‘JQb‘,‘JQB‘);            $("#b").text(window.localStorage.getItem(‘JQb‘));        });    </script></head><body>    <p id="a"></p>    <p id="b"></p></body></html>

運行結果: 

註:typeOf(localStorage.keyName)可與”undefined”進行判斷該索引值是否已存在

JQuery和JS操作LocalStorage/SessionStorage的方法(轉)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.