HTML5 Web存儲的兩種方法使用
localStorage和sessionStorage
參考:
http://www.cnblogs.com/taoweiji/archive/2012/12/08/2808997.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<style type="text/css">
textarea {
width: 300px;
height: 300px;
}
.button {
width: 100px;
}
</style>
</head>
<body onload="init()">
<script type="text/javascript">
//使用HTML5 Web存儲的localStorage和sessionStorage方式進行Web頁面數據本地存儲。
//頁面參考如下圖,能將頁面上的數據進行本地存儲。並能讀取存儲的數據顯示在頁面上。
var t1;
var t2;
var oStorage;
var oStorage;
function init() {//初始化t1,t2
t1 = document.getElementById("t1");
t2 = document.getElementById("t2");
sStorage = window.sessionStorage;
lStorage = window.localStorage
}
function saveSession() {
sStorage.mydata = t2.value;
t1.value += "sessionStorage保存mydata:" + t2.value + "\n";
}
function readSession() {
t1.value += "sessionStorage讀取mydata:" + sStorage.mydata + "\n";
}
function cleanSession() {
t1.value += "sessionStorage清除mydata:" + sStorage.mydata + "\n";
sStorage.removeItem("mydata");
}
function saveStorage() {
lStorage.mydata = t2.value;
t1.value += "localStorage保存mydata:" + t2.value + "\n";
}
function readStorage() {
t1.value += "localStorage讀取mydata:" + lStorage.mydata + "\n";
}
function cleanStorage() {
t1.value += "localStorage清除mydata:" + lStorage.mydata + "\n";
lStorage.removeItem("mydata");
}
</script>
<div>
<textarea id="t1"></textarea><br />
<label>需要保存的數據: </label>
<input type="text" id="t2" /><br />
<input type="button" class="button" onclick="saveSession()" name="b1" value="session保存" />
<input type="button" class="button" onclick="readSession()" value="session讀取" />
<input type="button" class="button" onclick="cleanSession()" value="session清除" /><br />
<input type="button" class="button" onclick="saveStorage()" value="local保存" />
<input type="button" class="button" onclick="readStorage()" value="local讀取" />
<input type="button" class="button" onclick="cleanStorage()" value="local清除" />
</div>
</body>
</html>
