<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="jquery.1.4.2.min.js"></script>
<script>
function MyClick1(){
var userName=$("#txtUserName").val();
var pwd=$("#txtPwd").val();
// sessionStorage.setItem("k_username",userName);
// sessionStorage.setItem("k_pwd",pwd);
localStorage.setItem("k_username",userName);
localStorage.setItem("k_pwd",pwd);
alert("存储成功");
}
function MyClick2(){
localStorage.removeItem("k_username"); //删除k_username的缓存
localStorage.removeItem("k_pwd"); //删除k_pwd的缓存
localStorage.clear(); //删除所有缓存
// alert(localStorage.getItem("k_username"));
// alert(localStorage.getItem("k_pwd"));
// alert(sessionStorage.getItem("k_username"));
// alert(sessionStorage.getItem("k_pwd"));
}
</script>
</head>
<body>
<input type="text" id="txtUserName">
<input type="text" id="txtPwd">
<input type="button" value="按钮1" onclick="MyClick1()">
<input type="button" value="按钮2" onclick="MyClick2()">
</body>
</html>
HTML5 提供了两种在客户端存储数据的新方法:
- localStorage - 没有时间限制的数据存储,第二天、第二周或下一年之后,数据依然可用。
- sessionStorage - 针对一个 session 的数据存储,当用户关闭浏览器窗口后,数据会被删除。
留言板案例:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="jquery.1.4.2.min.js"></script>
<script type="text/javascript">
$(function(){
if(localStorage.getItem("k_con")!==null){
"k_con",$("#DCon").html(localStorage.getItem("k_con"));
}
});
function PostCon(){
var sCon=$("#trCon").val();
$("#DCon").append("<div>" +sCon + "</div>" );
localStorage.setItem("k_con",$("#DCon").html());
}
//清除
function Clear(){
$("#DCon").html("");
$("#trCon").val("");
localStorage.clear();
}
</script>
</head>
<body>
<div><textarea id="trCon" cols="30" rows="8"></textarea></div>
<div><input type="button" value="发表" onclick="PostCon()"><input type="button" value="清除" onclick="Clear()"></div>
<div id="DCon"></div>
</body>
</html>