HTML5存储

摘要:

  数据存储是每一个站点必不可少的功能,在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

 1 <!doctype html>
 2 <html>
 3 <head>
 4     <title>LocalStorage</title>
 5     <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
 6     <style>
 7         #count {
 8             width: 500px;
 9             height: 500px;
10             background-color:#D3D3D3; 
11             margin:0 auto;
12         }
13     </style>
14     <script src="http://cdn.staticfile.org/jquery/2.0.0/jquery.min.js"></script>
15 </head>
16 <body>
17     <form method="post" action="">
18      <textarea id="count" name="count"></textarea><br />
19      <input type="button" name="button" id="sub" value="提交">
20      </form>
21     <script>
22           $(function(){
23             var data = new Array();
24             var json ="";
25             var storage = window.localStorage;
26             
27             $("#sub").click(function(){
28                 if(!storage.getItem("content")){
29                     storage.setItem("content", JSON.stringify($("#count").val().split('
')));
30                 } else {
31                     var content = JSON.parse(storage.getItem("content"));
32                     if($.isArray(content)) {
33                         storage.setItem("content", JSON.stringify(content.concat($("#count").val().split('
'))));
34                     } else {
35                         storage.setItem("content", JSON.stringify($("#count").val().split('
').push(content)));
36                     }
37                 }
38                 $("#count").val("");
39                 location.href = 'see.html';
40             });
41         })
42     </script>
43 </body>
44 </html>

see.html

 1 <!doctype html>
 2 <html>
 3 <head>
 4     <title>NoteBook</title>
 5     <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
 6     <style>
 7         #conten {
 8             background-color: #E1C97F;
 9             width: 500px;
10             height: 600px;
11             margin: 0 0 0 500px;
12         }
13         .stor {
14             padding: 10px 10px;
15             border-bottom: 1px dotted black;
16         }
17         .check {
18             float: right;
19         }
20         #back {
21             margin-left: 700px;
22         }
23     </style>
24     <script src="http://cdn.staticfile.org/jquery/2.0.0/jquery.min.js"></script>
25 </head>
26 <body>
27     <div id="conten">
28     </div>
29     <input type="button" name="button" id="back" value="返回">
30     <script>
31         $(function(){
32             var storage = window.localStorage;
33             var newjson = JSON.parse(storage.getItem('content'));
34             for(var i=0;i<newjson.length;i++){
35                 var htm = "<p class='stor'>"+newjson[i]+"</p>";
36                 $(htm).appendTo("#conten");
37             }
38             $('#back').click(function() {
39                 location.href = 'edit.html';
40             });
41         });
42     </script>
43 </body>
44 </html>

效果图

附录:

TopicDescription

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.

原文地址:https://www.cnblogs.com/xiyangbaixue/p/4118417.html