下面的代码设置了一个本地存储变量,每次访问这个页面时都可以访问该变量,甚至是下次打开窗口时:
XML/HTML Code复制内容到剪贴板
<!DOCTYPE HTML>
<html>
<body>
<script type="text/javascript">
if( localStorage.hits ){
localStorage.hits = Number(localStorage.hits) +1;
}else{
localStorage.hits = 1;
}
document.write("Total Hits :" + localStorage.hits );
</script>
<p>Refresh the page to increase number of hits.</p>
<p>Close the window and open it again and check the result.</p>
</body>
</html>
便于学习上述概念 – 请进行在线练习。
删除 Web 存储
在本地机器上存储敏感数据可能是危险的,可能会留下安全隐患。
_会话存储数据_在会话终止之后将由浏览器立即删除。
要清除本地存储设置需要调用 localStorage.remove(‘key’);这个 ‘key’ 就是我们想要移除的值对应的键。如果想要清除所有设置,需要调用 localStorage.clear() 方法。
下面的代码会完全清除本地存储:
XML/HTML Code复制内容到剪贴板
<!DOCTYPE HTML>
<html>
<body>
<script type="text/javascript">
localStorage.clear();
// Reset number of hits.
if( localStorage.hits ){
localStorage.hits = Number(localStorage.hits) +1;
}else{
localStorage.hits = 1;
}
document.write("Total Hits :" + localStorage.hits );
</script>
<p>Refreshing the page would not to increase hit counter.</p>
<p>Close the window and open it again and check the result.</p>









