【温故而知新-Javascript】使用Web存储
Web存储允许我们在浏览器里保存简单的键/值数据。Web存储和cookie很相似,但它有着更好的实现方式,能保存的数据量也很大。这两种类型共享相同的机制,但是被保存数据的可见性和寿命存在区别。
PS:还有一种存储规范名为“索引数据库API”(Indexed Database API),它允许保存富格式数据和进行SQL风格的查询。
1.使用本地存储
我们可以通过全局属性 localStorage访问本地存储功能。这个属性会返回一个Storage 对象,下表对其进行了介绍。Storage 对象被用来保存键/值形式的字符串对。

Storage 对象可用来存储键/值对,其中键和值都是字符串。键必须是惟一的,这就意味着如果我们用 Storage对象里已经存在的键调用setItem方法,就会更新它的值。下面的示例展示了如何添加、修改和清除本地存储中数据。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>使用本地存储</title>
<style>
body > * {float: left;}
table {border-collapse: collapse;margin-left:50px; }
th,td {padding: 4px;}
th {text-align: right;}
input {border: thin solid black;padding: 2px;}
label {min-width: 50px;display: inline-block;text-align: right;}
#countmsg,#buttons {margin-left: 50px;margin-top: 5px;margin-bottom: 5px;}
</style>
</head>
<body>
<div>
<div><label>Key:</label><input id="key" placeholder="Enter Key" /></div>
<div><label>Value:</label><input id="value" placeholder="Enter Value" /></div>
<div id="buttons">
<button id="add">Add</button>
<button id="clear">Clear</button>
</div>
<p id="countmsg">These are <span id="count"></span> items </p>
</div>
<table id="data" border="1">
<tr><th>Item Count:</th><td id="count">-</td> </tr>
</table>
<script>
displayData();
var buttons = document.getElementsByTagName("button");
for(var i=0;i<buttons.length;i++){
buttons[i].onclick = handleButtonPress;
}
function handleButtonPress(e){
switch (e.target.id){
case 'add':
var key = document.getElementById("key").value;
var value = document.getElementById("value").value;
localStorage.setItem(key,value);
displayData();
break;
case 'clear':
localStorage.clear();
displayData();
break;
}
}
function displayData(){
var tableElem = document.getElementById("data");
tableElem.innerHTML = "";
var itemCount = localStorage.length;
document.getElementById("count").innerHTML = itemCount;
for(var i=0;i<itemCount;i++){
var key = localStorage.key(i);
var val = localStorage[key];
tableElem.innerHTML += "<tr><th>" + key + ":</th><td>" + val + "</td></tr>";
}
}
</script>
</body>
</html>
此例报告了本地存储中的项目数量,并枚举已保存的键/值对来填充一个表格元素。这里添加了两个button元素,在Add按钮被按下时将他们的内容保存为项目。在响应Clear按钮时,会清除本地存储中的内容。其显示效果如下:

浏览器不会删除我们用 localStorage对象添加的数据,除非用户自己清除浏览数据。
监听存储事件
通过本地存储功能保存的数据对所有来源相同的文档都是可用的。某个文档对本地存储进行修改时会触发storage事件,我们可以监听其他同源文档上的这个事件来确保我们能跟上最新的变化。
与storage事件同时指派的对象是一个StorageEvent对象,它的成员如下表所示:

下面的示例展示了一个文档,它会监听并编录本地存储对象上触发的事件。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>编录本地存储事件</title>
<style>
table {border-collapse:collapse; }
th,td {padding: 4px;}
</style>
</head>
<body>
<table id="data" border="1">
<tr>
<th>key</th>
<th>oldValue</th>
<th>newValue</th>
<th>url</th>
<th>storageArea</th>
</tr>
</table>
<script>
var tableElem = document.getElementById("data");
window.onstorage = handleStorage;
function handleStorage(e){
var row = "<tr>";
row += "<td>" + e.key + "</td>";
row += "<td>" + e.oldValue + "</td>";
row += "<td>" + e.newValue + "</td>";
row += "<td>" + e.url + "</td>";
row += "<td>" + (e.storageArea == localStorage) + "</td>";
row += "</tr>";
tableElem.innerHTML += row;
}
</script>
</body>
</html>
storage事件是通过Window对象触发的,此对象可以来自共享被改动存储的任何一个文档。此例中,每次接收到事件时都会给table元素添加一个新行,演示效果如下:

图中的事件展示了给本地存储添加新项目的过程。url属性能帮助我们了解是哪个文档触发了变化。storageArea属性会返回发生变化的Storage对象,它可以是本地或会话存储对象。此例只接收来自本地存储对象的事件。
PS:这些事件不会再制造变化的文档内指派。
2. 使用会话存储
会话存储(session storage)的工作方式和本地存储很接近,不同之处在于数据是各个浏览上下文私有的,会在文档被关闭时移除。我们通过全局变量 sessionStorage访问会话存储,它会返回一个Storage对象。下面的例子展示了会话存储的用法:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>使用会话存储</title>
<style>
body > * {float: left;}
table {border-collapse: collapse;margin-left:50px; }
th,td {padding: 4px;}
th {text-align: right;}
input {border: thin solid black;padding: 2px;}
label {min-width: 50px;display: inline-block;text-align: right;}
#countmsg,#buttons {margin-left: 50px;margin-top: 5px;margin-bottom: 5px;}
</style>
</head>
<body>
<div>
<div><label>Key:</label><input id="key" placeholder="Enter Key" /></div>
<div><label>Value:</label><input id="value" placeholder="Enter Value" /></div>
<div id="buttons">
<button id="add">Add</button>
<button id="clear">Clear</button>
</div>
<p id="countmsg">These are <span id="count"></span> items </p>
</div>
<table id="data" border="1">
<tr><th>Item Count:</th><td id="count">-</td> </tr>
</table>
<script>
displayData();
var buttons = document.getElementsByTagName("button");
for(var i=0;i<buttons.length;i++){
buttons[i].onclick = handleButtonPress;
}
function handleButtonPress(e){
switch (e.target.id){
case 'add':
var key = document.getElementById("key").value;
var value = document.getElementById("value").value;
sessionStorage.setItem(key,value);
displayData();
break;
case 'clear':
sessionStorage.clear();
displayData();
break;
}
}
function displayData(){
var tableElem = document.getElementById("data");
tableElem.innerHTML = "";
var itemCount = sessionStorage.length;
document.getElementById("count").innerHTML = itemCount;
for(var i=0;i<itemCount;i++){
var key = sessionStorage.key(i);
var val = sessionStorage[key];
tableElem.innerHTML += "<tr><th>" + key + ":</th><td>" + val + "</td></tr>";
}
}
</script>
</body>
</html>
此例的工作方式和前面本地存储的例子很接近,不同之处在于可见性和寿命受到限制。这些限制会影响storage事件的处理方式:前面提到的storage事件只会在共享存储的文档中触发。对于会话存储,这就意味着事件只会在内嵌文档中触发,比如 iframe里的文档。修改前一示例如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>使用会话存储的storage事件</title>
<style>
body > * {float: left;}
table {border-collapse: collapse;margin-left:50px; }
th,td {padding: 4px;}
th {text-align: right;}
input {border: thin solid black;padding: 2px;}
label {min-width: 50px;display: inline-block;text-align: right;}
#countmsg,#buttons {margin-left: 50px;margin-top: 5px;margin-bottom: 5px;}
iframe {clear: left;}
</style>
</head>
<body>
<div>
<div><label>Key:</label><input id="key" placeholder="Enter Key" /></div>
<div><label>Value:</label><input id="value" placeholder="Enter Value" /></div>
<div id="buttons">
<button id="add">Add</button>
<button id="clear">Clear</button>
</div>
<p id="countmsg">These are <span id="count"></span> items </p>
</div>
<table id="data" border="1">
<tr><th>Item Count:</th><td id="count">-</td> </tr>
</table>
<br />
<iframe src="storage-02.html" width="666" height="222"></iframe></div>
<script>
displayData();
var buttons = document.getElementsByTagName("button");
for(var i=0;i<buttons.length;i++){
buttons[i].onclick = handleButtonPress;
}
function handleButtonPress(e){
switch (e.target.id){
case 'add':
var key = document.getElementById("key").value;
var value = document.getElementById("value").value;
sessionStorage.setItem(key,value)
displayData();
break;
case 'clear':
sessionStorage.clear();
displayData();
break;
}
}
function displayData(){
var tableElem = document.getElementById("data");
tableElem.innerHTML = "";
var itemCount = sessionStorage.length;
document.getElementById("count").innerHTML = itemCount;
for(var i=0;i<itemCount;i++){
var key = sessionStorage.key(i);
var val = sessionStorage[key];
tableElem.innerHTML += "<tr><th>" + key + ":</th><td>" + val + "</td></tr>";
}
}
</script>
</body>
</html>
其演示效果如下:

来源:《HTML5权威指南》(《The Definitive Guide to HTML5》)
【温故而知新-Javascript】使用Web存储的更多相关文章
- 《JavaScript》web客户端存储
Web存储: 兼容IE8在内的所有主流浏览器,不兼容早期浏览器:支持大容量但非无限量 LocalStorage和sessionStorage是window对象的两个属性,这两个属性都代表同一个stor ...
- 临时存存储页面上的数据---Web存储
HTML5 Web存储的两种方法使用 localStorage和sessionStorage 参考: http://www.cnblogs.com/taoweiji/archive/2012/12/0 ...
- 【读书笔记】HTML5 Web存储
PS:这里讲web存储,主要是在客户端存储的一些技术:cookie,localstorage,sessionstorage,WebSQL. Cookie Cookie是HTML4中在客户端 ...
- Web存储(Web Storage)的浏览器支持情况
所有很酷的功能特征的出现最关键的就是浏览器的支持情况,幸运的是,所有的现代浏览器都支持HTML5 Web存储(Web Storage),从IE8开始也支持它.HTML5 Web存储(Web Stora ...
- 全 Javascript 的 Web 开发架构:MEAN
http://developer.51cto.com/art/201404/434759.htm 全 Javascript 的 Web 开发架构:MEAN 引言 最近在Angular社区的原型开发者间 ...
- HTML5 Web存储(Web Storage)技术及用法
在如今的Web开发中,HTML5是大家讨论的最大一个话题.HTML5提供的新功能特征使得Web程序员如虎添翼,并免去了以往钻研各种方法来让网站更好.更快.更灵活的气力.这些新功能中有一个非常让我感兴趣 ...
- HTML5 总结-Web存储-7
HTML 5 Web 存储 在客户端存储数据 HTML5 提供了两种在客户端存储数据的新方法: localStorage - 没有时间限制的数据存储 sessionStorage - 针对一个 ses ...
- HTML5分析实战Web存储机制(Web Storage)
Web Storage它是Key-Value在持久性数据存储的形式.Web Storage为了克服cookie把所引起的一些限制.当数据需要严格格控制client准时,没有必要不断地发回数据serve ...
- web存储之webstorage
web存储分类 客户端和服务端 认识web存储 随着web应用的发展,是的客户端存储的用途越来越多,然而实现客户端端存储的方式也是越来越多样化.最简单最兼容的方式就是cookie,但作为真正的客户端存 ...
随机推荐
- 带给您灵感的25个最新鲜的 HTML5 网站
感谢 HTML5 带来的惊人的先进特性,在未来几年,HTML5 将会继续发挥巨大的推动作用,不仅是在 Web 应用中,网页设计领域也会有新的变革.今天,我们在这里集合了能够带给您灵感的25个最新鲜的 ...
- 百度地图API使用方法详解
最近做了个项目,其中项目中有个需求需要用到百度地图进行导航,通过查阅相关资料参考百度地图api完成了一个例子. API地址:http://developer.baidu.com/map/jsdemo. ...
- crystal
1.在*{margin:0;padding:0;}下,标签自带样式会失去效果,如:blockquote.table下cellpadding,align等. 2.标签自带属性样式没有css高. 3.在c ...
- scroll事件实现监控滚动条并分页显示示例(zepto.js)
scroll事件实现监控滚动条并分页显示示例(zepto.js ) 需求:在APP落地页上的底部位置显示此前其他用户的购买记录,要求此div盒子只显示3条半,但一页有10条,div内的滑动条滑到一页 ...
- C#遍历得到checkboxlist选中值和设置选中项
得到选中项的value值并拼接成一个字符串返回 public string GetChecked(CheckBoxList checkList, string separator) { string ...
- User Profile Service Application 配置同步连接时,报 MOSS MA not found
最近在试着配置"我的网站",不知什么原因在配置同步连接时报:MOSS MA not found 搜索发现,需要启动Forefront Identity Manager Servic ...
- ios7 tableview被navigationbar挡住
用ego下拉刷新的时候,每次在ios7时,tableview都会上移...导致被navagationbar挡住.ios6是正常的,于是在init的时候添加如下代码... NSComparisonRes ...
- JavaScript学习01 语言简介、基本使用和变量声明
JavaScript语言简介.基本使用和变量声明 JavaScript是网景(Netscape)公司开发的一种基于客户端浏览器.面向对象.事件驱动式的网页脚本语言. JavaScript的前身叫Liv ...
- C语言堆栈入门——堆和栈的区别
来看一个网上很流行的经典例子: main.cpp int a = 0; 全局初始化区 char *p1; 全局未初始化区 main() { int b; 栈 char s[] = "abc& ...
- phonegap创建的ios项目推送消息出现闪退现象
使用phonegap创建的ios项目,推送消息时,当程序在前台运行或者在后台运行状态下,推送消息过来,可以解析并且跳转: 但是在程序从后台退出的状态下,当消息推送过来的时候,点击通知栏,打开程序,程序 ...