1. 程式人生 > >web storage 簡單的網頁留言版

web storage 簡單的網頁留言版

alt element doc logs log als nbsp src mts

html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>簡單的網頁留言版</title>
		<script type="text/javascript" src="js/test6.js" ></script>
	</head>
	<body>
		<h1>簡單的網頁留言版</h1>
		
		<textarea id="demo" cols="60" rows="10"></textarea>
		<br>
		<input type="button"  value="保存" onclick="saveStorage(‘demo‘);">
		<input type="button"  value="清除" onclick="clearStorage(‘msg‘);">
		<input type="button"  value="讀取" onclick="loadStorage(‘msg‘);">
		<hr>
		<p id="msg"></p>
	</body>
</html>

  js

function saveStorage(id) {
	var data=document.getElementById(id).value;
	var time=new Date().getTime();
	localStorage.setItem(time,data);
	alert("數據保存成功");
}
function loadStorage(id){  
    var result = ‘<table border="1">‘;  
    for(var i = 0;i < localStorage.length;i++){ //localStorage.length所有保存在localStorage中的數據條數  
        var key = localStorage.key(i); //得到localStorage中與相應索引號對應的數據  
        var value = localStorage.getItem(key);  
        var date = new Date();  
        date.setTime(key);  
        var datestr = date.toGMTString();  
        result += ‘<tr><td>‘ + value + ‘</td><td>‘ + datestr + ‘</td></tr>‘;  
    }  
    result += ‘</table>‘;  
    var target = document.getElementById(id);  
    target.innerHTML = result;  
}  
//將localStorage中保存的數據全部清除  
function clearStorage(id){  
    localStorage.clear();  
    alert("全部數據被清除");  
    loadStorage(‘msg‘);  
}  

  效果:

技術分享

web storage 簡單的網頁留言版