HTML5之WEB Storage

來源:互聯網
上載者:User

標籤:自己   ane   技術分享   chrome   scroll   http   bind   get   lin   

什麼是HTML5 web storage?

使用HTML5,web頁面能夠使用使用者的瀏覽器本地儲存資料。

在曾經,通常我們使用cookie來儲存使用者資料。然而使用web儲存更加安全和高速。

資料不再包括在每個server請求中,僅僅存在你須要的時候。同一時候我們也能夠儲存大量資料,而不影響網站的效能。

資料都儲存成key/value形式,一個web頁面僅僅能夠訪問自己的資料。

瀏覽器支援

IE8+,Firefox,Chrome。Opera和Safari 5都支援這個特性。

注意IE7和更早版本號碼不支援這個特性。

localStorage和sessionStorage

這裡有倆個新的用來儲存資料的屬性:

  • localStorage - 沒有到期時間的方式儲存資料 
  • sessionStorage - 儲存資料到session

在使用web storage之前,檢查瀏覽器是否支援localStorage和sessionStorage:

 
  1. if(typeof(Storage)!=="undefined"){
  2. // Yes! localStorage and sessionStorage support!
  3. // Some code.....
  4. }else{
  5. // Sorry! No web storage support..
  6. }
localStorage Object

localStorage對象儲存資料沒有到期時間的問題。

資料在瀏覽器關閉後不會刪除。並且一直有效。

 
  1. localStorage.lastname="Smith";
  2. document.getElementById("result").innerHTML="Last name: "
  3. + localStorage.lastname;
線上示範

代碼說明:

  • 建立了一個localStorage 索引值對。使用key="lastname", value="Smith" 。
  • 得到lastname相應的值,而且賦予id=result的元素

小技巧:索引值對會以字串方式儲存。記住在必要的時候將他們轉為其它格式

以下的範例計算了一個使用者點擊button的次數。

在這段代碼中,將會把值轉化為數字。這樣能夠使用加法:

 
  1. if (localStorage.clickcount){
  2. localStorage.clickcount=Number(localStorage.clickcount)+1;
  3. }else{
  4. localStorage.clickcount=1;
  5. }
  6. document.getElementById("result").innerHTML="You have clicked the button " + localStorage.clickcount + " time(s).";
線上示範sessionStorage對象

sessionStorage對象和localStorage對象類似,除了儲存的資料僅僅在當前session中有效。資料將會在使用者關閉瀏覽器表單時失效。

以下代碼在當前的session中計算了使用者點擊的次數:

 
  1. if (sessionStorage.clickcount){
  2. sessionStorage.clickcount=Number(sessionStorage.clickcount)+1;
  3. }else{
  4. sessionStorage.clickcount=1;
  5. }
  6. document.getElementById("result").innerHTML="You have clicked the button " + sessionStorage.clickcount + " time(s) in this session.";

HTML5之WEB Storage

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.