一、Cookie LocalStorage SessionStorage
1、共同点: 都是浏览器的本地存储 2、区别: (图片来源牛客网)
二、代码示例
1、HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML5-Web存储</title>
<script src="storage.js"></script>
</head>
<body>
<button type="button" onclick="clickCounterLocal()">localStorage</button>
<div id="resultLocal"></div>
<p>请点击按钮使计数器递增。</p>
<p>关闭浏览器或标签页后再打开,不会重置</p>
<button type="button" onclick="clickCounterSession()">sessionStorage</button>
<div id="resultSession"></div>
<p>请点击按钮使计数器递增。</p>
<p>关闭浏览器或标签页后,计数器重置</p>
</body>
</html>
2、JS
function clickCounterLocal() {
if (typeof (Storage) == "undefined") {
document.getElementById("result").innerHTML = "抱歉!您的浏览器不支持Web Storage!";
} else {
if (!localStorage.clickcountlocal) {
localStorage.clickcountlocal = 1;
} else {
localStorage.clickcountlocal = Number(localStorage.clickcountlocal) + 1;
}
document.getElementById("resultLocal").innerHTML = "您已经点击这个按钮" + localStorage.clickcountlocal + "次";
}
}
localStorage.removeItem("clickcount");
function clickCounterSession() {
if (typeof (Storage) == "undefined") {
document.getElementById("resultSession").innerHTML = "抱歉!您的浏览器不支持Web Storage!";
} else {
if (!sessionStorage.clickcountsession) {
sessionStorage.setItem("clickcountsession", "1");
} else {
sessionStorage.clickcountsession = Number(sessionStorage.clickcountsession) + 1;
}
document.getElementById("resultSession").innerHTML = "您已经点击这个按钮" + sessionStorage.clickcountsession + "次";
}
}
3、结果
|