蠻討厭IE的,因為他常常需要特別照顧,就像DOM Storage(sessionStorage和localStorage)只能支持IE8+,對于以下的只能使用userData。
?
原理:通過在document元素后面附加一個專屬的“DHTML行為”來實現客戶端存儲,
var memory=document.createElement("div");//創建一個元素memory.style.display="none";//將其隱藏memory.style.behavior="url('#default#userData')"; //附加userData行為document.body.appendChild(memory);//將其添加到document元素中
一旦給元素賦予了“userData”行為,該元素就擁有了load()和save()方法,load()方法用于載入存儲的數據。使用它的時候必須傳遞一個字符串作為參數——類似于一個文件名,該參數用來指定要載入的存儲數據。當數據載入的時候,就可以通過該元素的屬性來訪問這些名值對形式的數據。
?
可以使用getAttribute()來查詢這些數據,通過setAttribute()方法設置屬性,然后調用save()方法可以存儲性的數據,而要刪除數據,通過使用removeAttribute()方法,然后調用save()方法即可。
?
Methods | Description |
---|---|
getAttribute(attr) | 獲取存儲對象中屬性值 |
load(name) | 載入存儲數據對象 |
removeAttribute(attr) | 刪除存儲對象中的屬性 |
save(name) | 更新存儲數據對象 |
setAttribute(attr, value) | 設置存儲對象中的鍵對值 |
properties | ? |
expires | 數據的有效期 |
XMLDocument | Returns a reference to the XML Document of the persisted object. |
基于userData實現部分存儲API
/*基于IE的userData實現,只有在IE中有效,保存名為UserDataStorage.js*/function UserDataStorage(maxage){//創建一個document元素鼻骨附加userData行為//因此該元素得save()和loda()方法var memory=document.createElement("div");memory.style.display="none";memory.style.behavior="url('#default#userData')"; //附加userData行為 document.body.appendChild(memory);//如果傳遞了maxage參數(單位為秒),則將其設置為userData的有效期,以毫秒為單位if(maxage){var now=new Date().getTime(); //當前時間var expires=now+maxage*1000;//當前時間加上有效期就等于過期時間memory.expires=new Date(expires).toUTCString(); //設置userData的過期時間}//通過載入存儲的數據初始化memory元素//參數是任意的,只要是在保存的時候存在的就可以了memory.load("UserDataStorage"); //載入存儲數據this.getItem=function(key){ //通過屬性來獲取保存的值return memory.getAttribute(key) || null;};this.setItem=function(key,value){memory.setAttribute(key,value); //已設置屬性的形式來保存數據memory.save("UserDataStorage"); //保存數據改變后的狀態 };this.removeItem=function(key){memory.removeAttribute(key); //刪除存儲的數據memory.save("UserDataStorage"); //再次保存狀態 }}
?
因為以上只能針對ie所以要在最后寫上
<!--[if IE]><script src="UserDataStorage.js"></script><![endif]-->
?
userData允許存儲的數據量比cookie大,但是卻比localStorage以及sessionStorage允許存儲的數據量要小。