| 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>"); } } |
写一个最简单的,利用本地存储的计数器:
| var storage = window.localStorage; if (!storage.getItem("pageLoadCount")) storage.setItem("pageLoadCount",0); storage.pageLoadCount = parseInt(storage.getItem("pageLoadCount")) + 1;//必须格式转换 document.getElementByIdx_x("count").innerHTML = storage.pageLoadCount; showStorage(); |
不断刷新就能看到数字在一点点上涨,如下图所示:

需要注意的是,HTML5本地存储只能存字符串,任何格式存储的时候都会被自动转为字符串,所以读取的时候,需要自己进行类型的转换。这也就是上一段代码中parseInt必须要使用的原因。
另外,在iPhone/iPad上有时设置setItem()时会出现诡异的QUOTA_EXCEEDED_ERR错误,这时一般在setItem之前,先removeItem()就ok了。
HTML5的本地存储,还提供了一个storage事件,可以对键值对的改变进行监听,使用方法如下:
| if(window.addEventListener){ window.addEventListener("storage",handle_storage,false); }else if(window.attachEvent){ window.attachEvent("onstorage",handle_storage); } function handle_storage(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 |









