基於Web Storage的客戶端留言板

一 代碼

<!DOCTYPE html>
<html>
<head>
	<meta name="author" content="Yeeku.H.Lee(CrazyIt.org)" />
	<meta http-equiv="Content-Type" content="text/html; charset=GBK" />
	<title> 客戶端留言板 </title>
	<style type="text/css">
		table {
			border-collapse: collapse;
		}
		td , th{
			border: 1px solid #888;
			padding: 4px;
		}
	</style>
</head>
<body>
	<h2>客戶端留言板</h2>
	<textarea id="msg" name="msg" cols="50" rows="8"></textarea><br/>
	<input type="button" value="添加留言" οnclick="addMsg();"/>
	<input type="button" value="清除留言" οnclick="clearMsg();"/>
	<hr/>
	<table style="width:550px">
		<tr>
			<th>留言內容</th>
			<th>留言時間</th>
		</tr>
		<tbody id="show"></tbody>
	</table>
	<script type="text/javascript">
		// 加載留言信息
		var loadMsg = function()
		{
			var tb = document.getElementById("show");
			// 清空原來顯示的內容。
			tb.innerHTML = "";
			// 遍歷所有留言信息
			for(var i = 0 ; i < localStorage.length ; i++)
			{
				var key = localStorage.key(i);
				var date = new Date();
				date.setTime(key);
				// 獲取留言時間
				var datestr = date.toLocaleDateString()
					+ "&nbsp;" + date.toLocaleTimeString();
				// 獲取留言內容
				var value = localStorage.getItem(key);
				var row = tb.insertRow(i);
				// 添加第一個單元格,並顯示留言內容
				row.insertCell(0).innerHTML = value;
				// 添加第二個單元格,並顯示留言內容。
				row.insertCell(1).innerHTML = datestr;
			}
		}
		var addMsg = function()
		{
			var msgElement = document.getElementById("msg");
			var time = new Date().getTime();
			// 以當前時間爲key來保存留言信息
			localStorage.setItem(time , msgElement.value);
			msgElement.value = "";
			alert("數據已保存。");
			loadMsg();
		}
		function clearMsg()
		{
			// 清空Local Storage裏保存的數據。
			localStorage.clear();
			alert("全部留言信息已被清除。");
			loadMsg();
		}
		window.onload = loadMsg();
	</script>
</body>
</html>

 

二 運行效果

 
發佈了17 篇原創文章 · 獲贊 12 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章