数据存储是每一个站点必不可少的功能,在HTML5之前通过cookie可以实现本地数据存储。但是cookie只能存储4kb的数据,并且cookie是随http请求一起发送到服务端,这必然浪费了带宽。Web Storage是HTML5引入的一个非常重要的功能,可以在客户端本地存储数据,类似HTML4的cookie,但可实现功能要比cookie强大的多,Web Storage官方建议为每个网站5MB,每个浏览器存储数据大小不一致。
web storage分为两种,一种是localStorage,另一种是sessionStorage,两者的差别是sessionStorage会随着浏览器的关闭而被清楚掉,而localStorage会永久的保存在本地,除非人为的删除。数据是以对象的格式存储在本地,两种存储的方法是一样的。
浏览器:
方法:
增:
if(window.localStorage) { localStorage.setItem(‘key’, ‘value’); }
删:
if(window.localStorage) { localStorage.removeItem(‘key’); }
改:
与增方法一样
查:
if(window.localStorage) { localStorage.getItem(‘key’); }
删除所有数据:
if(window.localStorage) { localStorage.clear(); }
获取某个索引的key,或者是数据的key:
if(window.localStorage) { localStorage.setItem(‘key’, ‘data’); console.log(localStorage.key(‘data’)); // output key }
扩展方法:
因为数据是以对象形式存在本地,索引对象的操作符也可以使用
if(window.localStorage) { var storage = window.localStorage; storage.key1 = “text”; storage["key2"] = “test”; console.log(storage.key1); console.log(storage["key2"]); }
key()与length实现数据遍历:
if(window.localStorage) { var storage = window.localStorage; for (var i=0, l = storage.length; i < l; i++) { var key = storage.key(i); var value = storage.getItem(key); console.log(key + “=” + value); } }
window的storage事件:
当数据键值改变或者clear的时候,就会触发storage事件
if(window.localStorage) { if(window.addEventListener) { // 非IE window.addEventListener(“storage”,handler,false); } else if(window.attachEvent) { // IE window.attachEvent(“onstorage”,handler); } function handler(e){ } }
事件对象属性:
属性 | 类型 | 描述 |
key | String | 被添加、删除或者修改的key |
oldValue | Any | 被修改、删除之前的值,如果是新增的则返回null |
newValue | Any | 被修改、新增的值,如果是删除则返回null |
url/uri | String | 当前页面地址 |
Demo:
下面这个实例是一个在线记事本,数据存储在localStorage中。分为两个页面,一个是填写数据,另一个是查看
edit.html
<!doctype html> <html> <head> <title>LocalStorage</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <style> #count { width: 500px; height: 500px; background-color:#D3D3D3; margin:0 auto; } </style> <script src=" http://cdn.staticfile.org/jquery/2.0.0/jquery.min.js"></script > </head> <body> <form method="post" action=""> <textarea id="count" name="count"></textarea><br /> <input type="button" name="button" id="sub" value="提交"> </form> <script> $(function(){ var data = new Array(); var json =""; var storage = window.localStorage; $("#sub").click(function(){ if(!storage.getItem("content")){ storage.setItem("content", JSON.stringify($("#count").val().split('\n'))); } else { var content = JSON.parse(storage.getItem("content")); if($.isArray(content)) { storage.setItem("content", JSON.stringify(content.concat($("#count").val().split('\n')))); } else { storage.setItem("content", JSON.stringify($("#count").val().split('\n').push(content))); } } $("#count").val(""); location.href = 'see.html'; }); }) </script> </body> </html>
see.html
<!doctype html> <html> <head> <title>NoteBook</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <style> #conten { background-color: #E1C97F; width: 500px; height: 600px; margin: 0 0 0 500px; } .stor { padding: 10px 10px; border-bottom: 1px dotted black; } .check { float: right; } #back { margin-left: 700px; } </style> <script src=" http://cdn.staticfile.org/jquery/2.0.0/jquery.min.js"></script > </head> <body> <div id="conten"> </div> <input type="button" name="button" id="back" value="返回"> <script> $(function(){ var storage = window.localStorage; var newjson = JSON.parse(storage.getItem('content')); for(var i=0;i<newjson.length;i++){ var htm = "<p class='stor'>"+newjson[i]+"</p>"; $(htm).appendTo("#conten"); } $('#back').click(function() { location.href = 'edit.html'; }); }); </script> </body> </html>
效果图
附录:
Topic | Description |
---|---|
HTMLStorage | Represents the list of key/value pairs that have been assigned to a single storage area. |
clear | Removes all key/value pairs from the Web Storage area. |
getItem | Retrieves the current value associated with the Web Storage key. |
initStorageEvent | Initializes a new Document Object Model (DOM) storage event that thecreateEvent method created. |
key | Retrieves the key at the specified index in the collection. |
removeItem | Deletes a key/value pair from the Web Storage collection. |
setItem | Sets a key/value pair. |
key | Gets the key that is updated. |
length | Retrieves the length of the key/value list. |
localStorage | Retrieves the Web Storage area specific to the current document. |
newValue | Gets the new value of the key. |
oldValue | Gets the previous value of the key. |
remainingSpace | Retrieves the remaining memory space, in bytes, for the storage object. |
sessionStorage | Retrieves the Web Storage area for the session. |
storageArea | Gets the Storage object of the affected document. |
url | Gets the address of the document that the update affects. |