09-解决方案
17.2.2 解决方案
在下面的例子中有两个HTML页面。每个页面包含一组可选择元素。当元素选中和反选时,保存页面状态。通过在两个页面之间导航,你可以看到在用户浏览网站时,指定页面的状态是如何维护的。 sessionStorage
对象用于用户后续访问期间不需要持续存储的数据:
<!DOCTYPE html>
<html><head>
<title>17.2 Saving Application State for a Single Session</title>
<style>
.square {
width: 100px; height: 100px; margin: 15px;
background-color: gray; border: 3px solid white; }
.selected {
border: 3px solid orange; }
</style>
<script src="../../jquery-1.3.2.min.js"></script>
</head>
<body>
<h1>17.2 Saving Application State for a Single Session</h1>
<a href="one.html">page one</a>
<a href="two.html">page two</a>
<div id="one" class="square"></div>
<div id="two" class="square"></div>
<div id="three" class="square"></div>
</body></html>
两个HTML页面( one.html
和 two.html
)内容相同。下面的JavaScript代码负责管理每个页面的状态,每个页面反映过去的用户操作:
jQuery(document).ready(function() {
$('.square').each(function(){
if( sessionStorage[window.location + this.id] == 'true' ) {
$(this).addClass('selected');
}
});
$('.square').click(function() {
$(this).toggleClass('selected');
sessionStorage[window.location + this.id] = $(this).hasClass('selected');
return false;
});
});
当文档加载时,查询 sessionStorage
对象,获得组成当前URL的键码以及每个可选择方块的 id
。每个方块都应用了合适的CSS类。当单击一个方块时,切换CSS类影响其显示,它的状态也相应存储。每个方块的状态用当前URL和当前元素 id
配对生成的键码保存。