开发者社区> 夕阳白雪> 正文

HTML5存储

简介: 摘要:   数据存储是每一个站点必不可少的功能,在HTML5之前通过cookie可以实现本地数据存储。但是cookie只能存储4kb的数据,并且cookie是随http请求一起发送到服务端,这必然浪费了带宽。
+关注继续查看

摘要:

  数据存储是每一个站点必不可少的功能,在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('\n')));
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('\n'))));
34                     } else {
35                         storage.setItem("content", JSON.stringify($("#count").val().split('\n').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>

 

效果图

 

 

附录:

 

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.

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

相关文章
【Python】HTML中Base64存储的图片转为本地图片文件
【Python】HTML中Base64存储的图片转为本地图片文件
70 0
HTML中dom转成图片进行存储
做作业的时候,需要在手机上预览下,但是发现如果想在移动端上展示A4样子的作业还是挺麻烦的,最后还是准备通过图片来展示,然后移动端缩放呗。。
202 0
网站开发笔记——(【Django】html表单存储Mysql方法篇)
网站开发笔记——(【Django】html表单存储Mysql方法篇)
120 0
HTML5 Web 存储|学习笔记
快速学习 HTML5 Web 存储
55 0
07.HTML 5 Web 存储
(来自W3CSchool) 在客户端存储数据 HTML5 提供了两种在客户端存储数据的新方法: localStorage - 没有时间限制的数据存储 sessionStorage - 针对一个 session 的数据存储 之前,这些都是由 cookie 完成的。
1103 0
第89天:HTML5中 访问历史、全屏和网页存储API
一、访问历史 API 通过history对象实现前进、后退和刷新之类的操作 history新增的两个方法history.replaceState()和history.pushState()方法属于HTML5浏览器新增的属性,所以IE9以下的是不支持的。
936 0
HTML 5 Web 存储-sessionStorage和localStorage
HTML5 提供了两种在客户端存储数据的新方法: localStorage - 没有时间限制的数据存储 sessionStorage - 针对一个 session 的数据存储 sessionStorage用于本地存储一个会话(session)中的数据,这些数据只有在同一个会话中的页面才能访问并且当会话结束后数据也随之销毁。
894 0
+关注
夕阳白雪
前端开发工程师
文章
问答
文章排行榜
最热
最新
相关电子书
更多
天猫 HTML5 互动技术实践
立即下载
天猫HTML5互动技术实践
立即下载
《零基础HTML入门教程》
立即下载