DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> HTML基礎知識 >> HTML5詳解 >> HTML5 Web Storage
HTML5 Web Storage
編輯:HTML5詳解     

簡介

Html5 web storage, better than cookIEs.

  • more secure and faster
  • data store in name/value pairs
  • the storage limit is at least 5MB

 

 

1. 發展過程:

 

 

 

2. 浏覽器支持情況:

 

 

 

3. Html5 Web Storage 提供如下兩種對象:

  • window.localStorage - stores data with no expiration date  沒有過期日期
  • sessionStorage - stores data for one session (data is lost when the tab is closed) 

   兩者使用沒有區別,下面使用中以localStorage舉例

 

4. 基本使用:

 

使用前應該判斷浏覽器是否支持

if(typeof(Storage)!=="undefined")   {   // Code for localStorage/sessionStorage.
  } else   {   // Sorry! No Web Storage support..
  }

使用:

localStorage.setItem("name","wish");  // store
localStorage.name="wish"; localStorage["name"]="wish";  localStorage.getItem("name");  //retrIEve
 localStorage.removeItem("name");  //remove
 localStorage.clear();      //刪除所有
 localStorage.key(i);   // get key
 

注意: localStorage calls toString on all stored values.  所以如果是數字等類型也會轉化為String

5.例子

在google resource中查看:removeItem後改記錄消失

簡單頁面訪問計數:

使用localStorage:

if (localStorage.visitcount)
  {
  localStorage.visitcount = Number(localStorage.visitcount) + 1; //需要轉換類型
  }
else
  {
  localStorage.visitcount= 1;
  }
document.getElementById("visitTimes").innerHtml="You have visited " +
localStorage.visitcount+ " time(s).";  

使用sessionStorage:

if (sessionStorage.visitcount)
  {
  sessionStorage.visitcount = Number(sessionStorage.visitcount) + 1; //需要轉換類型
  }
else
  {
  sessionStorage.visitcount= 1;
  }
document.getElementById("visitTimes").innerHtml="You have visited " +
sessionStorage.visitcount+ " time(s).";

6.github上store.JS

  github地址:https://github.com/marcuswestin/store.JS/

  • 基於localStorage  :store.JS exposes a simple API for cross browser local storage
  • 無兼容性問題:store.JS uses localStorage when available, and falls back on the userData behavior in IE6 and IE7
  • 存儲時不會tostring: store.js uses JSON.stringify() and JSON.parse() on each call to store.set() and store.get()

  基本使用如下:

store.set("name", "wish")  // Store
 store.get("name")   // Get 
 store.remove("username")  // Remove "name"
 store.clear()  // Clear all keys
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved