<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>js window.localStorage</title>
<script src="../../lib/jquery/jquery-3.2.1.js"></script>
</head>
<body>
<div id="result"></div>
<p>
<button οnclick="clickCounter()">单击计数</button>
</p>
<div id="result2"></div>
<p>点击按钮查看数字会自动增加。</p>
<p>关闭浏览器,重新打开这个页面点击按钮,可以看到之前的数据是有保留的。</p>
<script>
/*功能:window.localStorage 的定义和使用
参考:https://www.runoob.com/jsref/prop-win-localstorage.html
知识点:
1.localStorage 和 sessionStorage 属性允许在浏览器中存储 key-value 键值对数据。
localStorage 用于长久保存整个网站的数据,保存的数据没有过期时间,直到手动去删除。
localStorage 属性是只读的。
提示: 如果你只想将数据保存在当前会话中,可以使用 sessionStorage 属性,
该数据对象临时保存同一窗口(或标签页)的数据,在关闭窗口或标签页之后将会删除这些数据。
localStorage.setItem("key", "value");
let value = localStorage.getItem("key");
localStorage.removeItem("key");
localStorage.clear();
let key = localStorage.key(index);
*/
// 判断浏览器是否支持
if (typeof (Storage) !== "undefined") {
// 1.
localStorage.setItem("name", "Smith");
// document.getElementById("result").innerHTML = localStorage.getItem("lastname");
$("#result").html(localStorage.getItem("name"));
} else {
$("#result").html("抱歉,你的浏览器不支持网络存储!");
}
function clickCounter() {
// 判断浏览器是否支持
if (window.localStorage) {
if (localStorage.clickcount) {
// console.log(typeof localStorage.clickcount); // string
localStorage.clickcount = Number(localStorage.clickcount) + 1;
} else {
localStorage.clickcount = 1;
}
$("#result2").html("你在按钮上已经点击了 " + localStorage.clickcount + " 次。");
} else {
$("#result").html("抱歉,你的浏览器不支持网络存储!");
}
}
function testLocalStorage() {
/*功能:测试localStorage。*/
if (!window.localStorage) {
alert("浏览器不支持localstorage");
return false;
} else {
let storage = window.localStorage;
console.log("storage:", storage);
// Storage {name: "Smith", length: 1}
// 写入字段 a
storage["a"] = 1;
// 写入字段 b
storage.b = 1;
// 写入字段 c
storage.setItem("c", '3');
console.log(typeof storage["a"]); // string
console.log(typeof storage["b"]); // string
console.log(typeof storage["c"]); // string
console.log("storage:", storage);
// Storage {a: "1", b: "1", c: "3", name: "Smith", length: 4}
// Storage {b: "1", c: "3", name: "Smith", a: "1", length: 4}
for (let i = 0; i < storage.length; i++) {
let key = storage.key(i);
console.log(key);
// a b c name
// b c name a
}
storage.clear();
console.log(storage);
// Storage {length: 0}
}
}
testLocalStorage();
</script>
</body>
</html>