推荐使用js-cookie
js-cookie
- 环境配置 CDN 或 套件命令 npm i js-cookie
语法
- 储存
Cookies.set(\'name\', \'value\')
- 储存(效期)
Cookies.set(\'name\', \'value\', { expires: 7 })
- 读取cookie
Cookies.get(\'name\')
-删除cookie
Cookies.remove(\'name\')
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h2 class="textContent"></h2>
<button class="SaveBtn">储存</button>
<button class="DeleteBtn">删除</button>
<script>
const SaveBtn = document.querySelector(".SaveBtn");
console.log(SaveBtn);
const DeleteBtn = document.querySelector(".DeleteBtn");
console.log(DeleteBtn);
const textContent = document.querySelector(".textContent");
console.log(textContent);
SaveBtn.addEventListener("click", () => {
// 储存
console.log("有触发");
Cookies.set("text", "我被储存");
const cat = Cookies.get("text");
textContent.innerHTML = cat;
});
DeleteBtn.addEventListener("click", () => {
// 移除显示
console.log("有触发");
Cookies.remove("text");
textContent.innerHTML = "";
});
</script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie@3.0.5/dist/js.cookie.min.js"></script>
</body>
</html>