localStorage对象

localStorage对象存储的数据没有时间限制,比如:它可以存储到第二天,第三周,半年,或二三年,只要您的电脑没有重新安装系统或更换硬盘,数据仍然会被保留着。

实例:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>localStorage</title>
<meta charset="utf-8" />
<style type="text/css"></style>
<script type="text/javascript">
if (typeof (Storage) !== "undefined") {
localStorage.englishName = "melao2006";
document.getElementById("pid").innerHTML = "lastName:" + localStorage.englishName;
}
else {
document.getElementById("pid").innerHTML = "Sorry!,您的浏览器不支持web存储";
}
</script>
</head>
<body>
<p id="pid"></p>
</body>
</html>

实例分析:

1、使用key="englishName"和value="melao2006"创建了一个localStorage键/值对形式来存储。

2、检查键为englishName的值插入到一个id="result"的元素中。

提示:键值对通常是以字符串的形式存储数据,您可以根据自己的数据要求转换格式。如:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<meta charset="utf-8" />
<style type="text/css"></style>
<script type="text/javascript">
function myFunction() {
if (typeof (Storage) !== "undefined")
{
if (localStorage.clickCount) {
localStorage.clickCount = Number(localStorage.clickCount) + 1;//转换成自己需要的数据格式
}
else {
localStorage.clickCount = 1;
}
document.getElementById("result").innerHTML = localStorage.clickCount;
}
else {
document.getElementById("pid").innerHTML = "Sorry!,您的浏览器不支持web存储";
}
}

</script>
</head>
<body>
<input type="button" onclick="myFunction()" value="点击按钮" />
<p>点击按钮查看计数器的增加</p>
<p>关闭浏览器窗口再一次打开,继续点击按钮,计算器的数字仍然在增加。</p>
<p id="result"></p>
</body>
</html>

 

posted @ 2015-11-19 16:55  melao2006  阅读(326)  评论(0编辑  收藏  举报