简单存储
HTML5 提供了四种在客户端存储数据的新方法,即localStorage 、sessionStorage、globalStorage、WebSql Database。 前面三个适用于存储较少的数据,而
Web Sql Database适用于存储大型的,复杂的数据,我习惯把前面的三个称之为小存储。
简单储存和cookie的区别
<h4>localStorage详解</h4>
localStorage / sessionStorage 都有相同的API 如:
①localStorage.length 获得storage 中的个数
②localStorage.key(n) 获得storage中第n个键值对的键
③localStorage.key=value
④localStorage.setItem(key,value) 添加
⑤localStorage.getItem(key) 获取
⑥localStorage.removeItem(key) 移除
⑦localStorage.clear() 清除
HTML:
<pre>用户名:<input type="text" name="names">
密码: <input type="password" name="pass">
是否保存:<input type="checkbox" name="box"></pre>
<h5>demo1,生命周期</h5>
JavaScript:
<pre>document.cookie = "zhangsan";
localStorage.setItem("name","lisi");
sessionStorage.setItem("name","wangwu");
在注释上面的三句话之后
alert(document.cookie);//浏览器关闭后没有
alert(localStorage.getItem("name"));//浏览器关闭后仍然存在
alert(sessionStorage.getItem("name"));//浏览器关闭后没有</pre>
<h5>demo2,账号密码的保存</h5>
JavaScript :
<pre>window.onload = function() {
var names = document.getElementsByName("names")[0],
pass = document.getElementsByName("pass")[0],
box = document.getElementsByName("box")[0];
names.value = localStorage.getItem("names")?localStorage.getItem("names"):"";
pass.value = localStorage.getItem("pass")?localStorage.getItem("pass"):"";
box.checked = names.value&&pass.value;
box.onclick = function() {
if (box.checked) {
localStorage.setItem("names", names.value);
localStorage.setItem("pass", pass.value);
box.checked = true;
} else {
localStorage.removeItem("names");
localStorage.removeItem("pass");
}
}
}
</pre>
<h5>demo3,刷新页面后之前写的数据仍然存在</h5>
JavaScript:
<pre>
window.onload=function () {
var title=document.getElementsByName("title")[0];
var con=document.getElementsByName("con")[0];
var login=document.getElementById("login");
if(sessionStorage.title||sessionStorage.con){
title.value=sessionStorage.title;
con.value=sessionStorage.con;
}
login.onclick=function () {
sessionStorage.title=title.value;
sessionStorage.con=con.value;
}
}
</pre>
HTML:
<pre>标题:<input type="text" name="title">
内容:<textarea rows=5 cols=15 name="con"></textarea>
<a href="test.php" id="login">登陆</a></pre>