HTML5 LocalStorage 本機存放區

來源:互聯網
上載者:User

標籤:


localStorage和sessionStorage一樣都是用來儲存用戶端臨時資訊的對象,他們均只能儲存字串類型的對象

localStorage生命週期是永久,這意味著除非使用者顯示在瀏覽器提供的UI上清除localStorage資訊,否則這些資訊將永遠存在
sessionStorage生命週期為當前視窗或標籤頁,一旦視窗或標籤頁被永久關閉了,那麼所有通過sessionStorage儲存的資料也就被清空了
ps:不同瀏覽器無法共用localStorage或sessionStorage中的資訊。相同瀏覽器的不同頁面間可以共用相同的localStorage(頁面屬於相同網域名稱和連接埠),但是不同頁面或標籤頁間無法共用sessionStorage的資訊。這裡需要注意的是,頁面及標籤頁僅指最上層視窗,如果一個標籤頁包含多個iframe標籤且他們屬於同源頁面,那麼他們之間是可以共用sessionStorage的

在HTML5中,本機存放區是一個window的屬性,包括localStorage和sessionStorage

1.首先自然是檢測瀏覽器是否支援本機存放區(如localStorage)。
    if(window.localStorage){
         alert(‘This browser supports localStorage‘);
    }else{
         alert(‘This browser does NOT support localStorage‘);
    }

2.往 localStorage 裡邊設值
    localStorage.name = ‘zs‘;//設定name為"zs"
    localStorage["name"] = "ls";//設定name為"ls"
    localStorage.setItem("name","ww");//設定name為"ww"

3.擷取localStorage裡邊的值
    localStorage.name
    localStorage["name"]
    localStorage.getItem("name")

    另外,HTML5還提供了一個key()方法
    var storage = window.localStorage;
    function showStorage(){
        for(var i=0;i<storage.length;i++){
         //key(i)獲得相應的鍵,再用getItem()方法獲得對應的值
         document.write(storage.key(i)+ " : " + storage.getItem(storage.key(i)) + "<br>");
        }
    }

4.清除localStorage裡邊的值
    localStorage.removeItem("name")        // 刪除name
    localStorage.clear()    //清除所有


5.localStorage 事件
    HTML5的本機存放區,還提供了一個storage事件,可以對索引值對的改變進行監聽,使用方法如下
    if(window.addEventListener){
        window.addEventListener("storage",handleStorage,false);
    }else if(window.attachEvent){
        window.attachEvent("onstorage",handleStorage);
    }
    function handleStorage(e){
        if(!e){e=window.event;}
         //showStorage();
    }

    對於事件變數e,是一個StorageEvent對象,提供了一些實用的屬性,可以很好的觀察索引值對的變化

 Property

 Type

 Description

 key

 String

 The named key that was added, removed, or moddified

 oldValue

 Any

 The previous value(now overwritten), or null if a new item was added

 newValue

 Any

 The new value, or null if an item was added

 url/uri

 String

 The page that called the method that triggered this change

 另外,目前javascript使用非常多的json格式,如果希望儲存在本地,可以直接調用JSON.stringify()將其轉為字串。讀取出來後調用JSON.parse()將字串轉為json格式

  var details = {author:"xxx","description":"xxx"};
  storage.setItem("details",JSON.stringify(details));
  details = JSON.parse(storage.getItem("details"));

 

封裝localStorage

    var LS = {
        set : function(key, value){
            //在iPhone/iPad上有時設定setItem()時會出現詭異的QUOTA_EXCEEDED_ERR錯誤
            //這時一般在setItem之前,先removeItem()就ok了
            if( this.get(key) !== null )
                this.remove(key);
            localStorage.setItem(key, value);
        },
        //查詢不存在的key時,有的瀏覽器返回undefined,這裡統一返回null
        get : function(key){
            var v = localStorage.getItem(key);
            return v === undefined ? null : v;
        },
        remove : function(key){ localStorage.removeItem(key); },
        clear : function(){ localStorage.clear(); },
        each : function(fn){
            var n = localStorage.length, i = 0, fn = fn || function(){}, key;
            for(; i<n; i++){
                key = localStorage.key(i);
                if( fn.call(this, key, this.get(key)) === false )
                    break;
                //如果內容被刪除,則總長度和索引都同步減少
                if( localStorage.length < n ){
                    n --;
                    i --;
                }
            }
        }
    }

 

 


   

HTML5 LocalStorage 本機存放區

聯繫我們

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