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.

相关文章
|
存储 前端开发 JavaScript
HTML中dom转成图片进行存储
做作业的时候,需要在手机上预览下,但是发现如果想在移动端上展示A4样子的作业还是挺麻烦的,最后还是准备通过图片来展示,然后移动端缩放呗。。
HTML中dom转成图片进行存储
|
5月前
|
存储 Web App开发 移动开发
HTML5在客户端存储数据的新方法——localStorage
HTML5在客户端存储数据的新方法——localStorage
77 0
|
10月前
|
存储 移动开发 JSON
前端|HTML5中的网络存储
前端|HTML5中的网络存储
95 0
|
11月前
|
存储 移动开发 前端开发
前端祖传三件套HTML的HTML5之Web存储 localStorage/sessionStorage
HTML5 是 Web 技术的重要更新,其中包括一些新特性。其中之一就是 Web 存储。Web 存储允许我们在客户端(浏览器)中存储数据,而不必依赖服务器。本文介绍两种常见的 Web 存储:localStorage 和 sessionStorage。
170 0
|
存储 Python
【Python】HTML中Base64存储的图片转为本地图片文件
【Python】HTML中Base64存储的图片转为本地图片文件
211 0
|
存储 移动开发 JavaScript
|
存储 移动开发 开发者
HTML5 Web 存储|学习笔记
快速学习 HTML5 Web 存储
111 0
HTML5 Web 存储|学习笔记
|
SQL Web App开发 存储
HTML5中的本地、WebSql、离线应用存储
1.   HTML5存储相关API a)   Localstorage 本地存储 b)   Web Sql DataBase 本地数据库存储 c)   .manifest 离线应用存储 2.   HTML5 localStorage 本地存储: a)   本地存储是一个window的属性:, 相当于一个大型的Cookie; b)   window.
1045 0
|
存储 JSON 数据格式
HTML5开发——轻量级JSON存储解决方案Lawnchair.js
Lawnchair是一个轻量级的移动应用程序数据持久化存储方案,同时也是客户端JSON文档存储方法,优点是短小,语法简洁,扩展性比较好。 现在做HTML5移动应用除了LocalStorage的兼容性比较好之外,SQL web database以及IndexedDB都处在僵局中,虽然有人叫嚣着“我们应该干掉 LocalStorage API”,但那是后话,现在也没得选择。
1149 0
|
存储 移动开发 JavaScript
07.HTML 5 Web 存储
(来自W3CSchool) 在客户端存储数据 HTML5 提供了两种在客户端存储数据的新方法: localStorage - 没有时间限制的数据存储 sessionStorage - 针对一个 session 的数据存储 之前,这些都是由 cookie 完成的。
1192 0