html5指南-5.使用web storage存储键值对的数据

2020-04-21 07:34:30易采站长站整理

}
</script>
</body>
</html>

我们在例1中增删改storage的数据,会在例2页面上显示出来。例2在chrome浏览器中运行正常,firefox没有反应,其他浏览器没有测试。
运行结果

3.使用session storage
session storage在使用上和local storage一样,只是他的访问性上只限于当前页面,并且页面关闭后会消失,我们通过sessionStorage来访问它。


<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
<style>
body > *{float: left;}
table{border-collapse: collapse;margin-left: 50px;}
th, td{padding: 4px;}
th{text-align: right;}
input{border: thin solid black;padding: 2px;}
label{min-width: 50px;display: inline-block;text-align: right;}
#countmsg, #buttons{margin-left: 50px;margin-top: 5px;margin-bottom: 5px;}
</style>
</head>
<body>
<div>
<div>
<label>Key:</label><input id=”key” placeholder=”Enter Key” /></div>
<div>
<label>Value:</label><input id=”value” placeholder=”Enter Value” /></div>
<div id=”buttons”>
<button id=”add”>Add</button>
<button id=”clear”>Clear</button>
</div>
<p id=”countmsg”>There are <span id=”count”></span>items</p>
</div>
<table id=”data” border=”1″>
<tr>
<th>Item Count:</th>
<td id=”count”>-</td>
</tr>
</table>
<iframe src=”storage.html” width=”500″ height=”175″></iframe>
<script>
displayData();
var buttons = document.getElementsByTagName(“button”);
for (var i = 0; i < buttons.length; i++) {
buttons[i].onclick = handleButtonPress;
}
function handleButtonPress(e) {
switch (e.target.id) {
case ‘add’:
var key = document.getElementById(“key”).value;
var value = document.getElementById(“value”).value;
sessionStorage.setItem(key, value);
break;
case ‘clear’:
sessionStorage.clear();
break;
}
displayData();
}
function displayData() {
var tableElement = document.getElementById(‘data’);
tableElement.innerHTML = ”;
var itemCount = sessionStorage.length;
document.getElementById(‘count’).innerHTML = itemCount;
for (var i = 0; i < itemCount; i++) {
var key = sessionStorage.key(i);