Day5
今日份内容:Web Storage中Local Storage的使用
Local Storage:与Session Storage用法基本相同,Local Storage以键值对(key-value)形式存储数据。Local Storage中的数据保存在客户端的存储介质上,无时间限制,不受浏览器关闭影响,用户可以自己清除数据。
Local Storage
- 熟悉Local Storage接口
- 使用Local Storage存储数据
内容
使用Local Storage存储在线用户信息
代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Local Storage</title>
<link rel="stylesheet" type="text/css" href="localStorage.css" />
</head>
<body>
<div class="container">
<dl>
<dt><img src="localStorage/images/longzhuLive.jpg"></dt>
<dd onclick="addFavorites('longzhu')">收藏</dd>
</dl>
<dl>
<dt><img src="localStorage/images/qieLive.jpg"></dt>
<dd onclick="addFavorites('qie')">收藏</dd>
</dl>
<dl>
<dt><img src="localStorage/images/douyuLive.jpg"></dt>
<dd onclick="addFavorites('douyu')">收藏</dd>
</dl>
<dl>
<dt><img src="localStorage/images/huyaLive.jpg"></dt>
<dd onclick="addFavorites('huya')">收藏</dd>
</dl>
</div>
<hr>
<table width="400px">
<caption>直播平台收藏列表</caption>
<thead>
<tr>
<th>在线用户</th>
<th width="180px">收藏时间</th>
<th>操作</th>
</tr>
</thead>
<tbody id="resultTable">
<tr>
<td colspan="3">暂未收藏</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
//清除localStorage中存储的数据
//localStorage.clear();
//直播平台数据集合
var liveChannels = [{
name: '龙珠直播',
key: 'longzhu'
},
{
name: '企鹅直播',
key: 'qie'
},
{
name: '斗鱼直播',
key: 'douyu'
},
{
name: '虎牙直播',
key: 'huya'
}
];
//收藏直播平台
function addFavorites(channel) {
var channelObject = searchChannel(channel);
var currentChannel = {
name: channelObject.name,
key: channel,
addTime: formateTime(new Date())
}
localStorage.setItem(channel, JSON.stringify(currentChannel));
showFavorites()
}
//显示已收藏的直播平台信息
function showFavorites() {
var result = "";
if (localStorage.length == 0) {
result = result + "<tr><td colspan = '3'>暂未收藏</td></tr>";
} else {
for (var j = 0; j < localStorage.length; j++) {
var key = localStorage.key(j);
var favorite = JSON.parse(localStorage.getItem(key));
result = result + "<tr><td>" + favorite.name + "</td><td>" + favorite.addTime + "</td>";
result = result + "<td><button onclick = deleteFavorite('" + favorite.key + "')>删除</button></td></tr>"
}
}
var resultTable = document.getElementById("resultTable");
resultTable.innerHTML = result;
}
//删除指定的收藏
function deleteFavorite(key) {
localStorage.removeItem(key);
showFavorites();
}
//在数据集合中进行检索
function searchChannel(channel) {
for (var i in liveChannels) {
if (liveChannels[i].key == channel) {
return liveChannels[i];
}
}
}
function formateTime(myDate) {
var year = myDate.getFullYear();
var month = myDate.getMonth() + 1;
var date = myDate.getDate();
var hour = myDate.getHours();
var minute = myDate.getMinutes();
var second = myDate.getSeconds();
var dateString = year + "年" + month + "月" + date + "日" + hour + ":" + minute + ":" + second;
return dateString;
}
showFavorites();
</script>
</body>
</html>
结果
PS
与Session Storage一样,在Local Storage中复杂信息也需要以JSON字符串形式存储。