HTML5 LocalStorage 本地存储
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 --;
}
}
}
}
出处:http://www.cnblogs.com/rsky
欢迎转载,但请务必注明出处。