簡單存儲
HTML5 提供了四種在客戶端存儲數(shù)據(jù)的新方法,即localStorage 雌贱、sessionStorage袱耽、globalStorage、WebSql Database裙盾。 前面三個適用于存儲較少的數(shù)據(jù),而
Web Sql Database適用于存儲大型的,復(fù)雜的數(shù)據(jù)他嫡,我習(xí)慣把前面的三個稱之為小存儲番官。
簡單儲存和cookie的區(qū)別
<h4>localStorage詳解</h4>
localStorage / sessionStorage 都有相同的API 如:
①localStorage.length 獲得storage 中的個數(shù)
②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);//瀏覽器關(guān)閉后沒有
alert(localStorage.getItem("name"));//瀏覽器關(guān)閉后仍然存在
alert(sessionStorage.getItem("name"));//瀏覽器關(guān)閉后沒有</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,刷新頁面后之前寫的數(shù)據(jù)仍然存在</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>標(biāo)題:<input type="text" name="title">
內(nèi)容:<textarea rows=5 cols=15 name="con"></textarea>
<a href="test.php" id="login">登陸</a></pre>