HTML5LocalStorage本地存储
说到本地存储,这玩意真是历尽千辛万苦才走到
最早的
userData
支持的情况如上图,
首先自然是检测浏览器是否支持本地存储。在
if(window.localStorage){alert(‘ThisbrowsersupportslocalStorage’);}else{alert(‘ThisbrowserdoesNOTsupportlocalStorage’);}
存储数据的方法就是直接给
localStorage.a=3;//localStorage["a"]="sfsf";//localStorage.setItem("b","isaac");//vara1=localStorage["a"];//vara2=localStorage.a;//varb=localStorage.getItem("b");//localStorage.removeItem("c");//
这里最推荐使用的自然是
varstorage=window.localStorage;functionshowStorage(){for(vari=0;i<storage.length;i++){//key(i)document.write(storage.key(i)+":"+storage.getItem(storage.key(i))+"<br>");}}
写一个最简单的,利用本地存储的计数器:
varstorage=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
if(window.addEventListener){window.addEventListener("storage",handle_storage,false);}elseif(window.attachEvent){window.attachEvent("onstorage",handle_storage);}functionhandle_storage(e){if(!e){e=window.event;}//showStorage();}
对于事件变量
Property
Type
Description
key
String
Thenamedkeythatwasadded,removed,ormoddified
oldValue
Any
Thepreviousvalue(nowoverwritten),ornullifanewitemwasadded
newValue
Any
Thenewvalue,ornullifanitemwasadded
url/uri
String
Thepagethatcalledthemethodthattriggeredthischange
这里添加两个键值对
<body><p>Youhaveviewedthispage<spanid="count">0</span>time(s).</p><p><inputtype="button"value="changeStorage"onClick="changeS()"/></p><script>varstorage=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();if(window.addEventListener){window.addEventListener("storage",handle_storage,false);}elseif(window.attachEvent){window.attachEvent("onstorage",handle_storage);}functionhandle_storage(e){if(!e){e=window.event;}showObject(e);}functionshowObject(obj){//递归显示objectif(!obj){return;}for(variinobj){if(typeof(obj[i])!="object"||obj[i]==null){document.write(i+":"+obj[i]+"<br/>");}else{document.write(i+":object"+"<br/>");}}}storage.setItem("a",5);functionchangeS(){//if(!storage.getItem("b")){storage.setItem("b",0);}storage.setItem(‘b’,parseInt(storage.getItem(‘b’))+1);}functionshowStorage(){//for(vari=0;i<storage.length;i++){//key(i)document.write(storage.key(i)+":"+storage.getItem(storage.key(i))+"<br>");}}</script></body>
测试发现,目前浏览器对这个支持不太好,仅
目前浏览器都带有很好的开发者调试功能,,下面分别是
另外,目前
大多数人想要改造这个世界,但却罕有人想改造自己。