npm i js-cookie
語法
Cookies.set('name', 'value')
Cookies.set('name', 'value', { expires: 7 })
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>