前置知识接上一篇
开始封装cookie export{}导出,并在html里面引入
// 开始封装setCookie
// 里面的四个参数,name = value,name是属性名,需要自己手动写
const setCookie = (name, value, maxAge, path) => {
// 添加cookie是document.cookie = "要添加的内容"
// 开始写要添加的内容,先定义一个变量来接收这个内容
// 格式是 "name = zhangsan; "
let cookieString = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;
if (typeof maxAge === "number") {
cookieString += `; max-age=${maxAge}`;
}
if (path) {
cookieString += `; path=${path}`;
}
document.cookie = cookieString;
};
// 获取cookie,要获取的是name这一项
// document.cookie
const getCookie = (name) => {
let cookieName;
let cookieValue;
// 先把获取到的所有的内容转成数组,并用一个变量来接收
const cookieArray = document.cookie.split("; ");
// 通过遍历for of,得到数组里面的每一项,
// 比如"name = zhangsan" "age = 10" "sex=male"
for (const item of cookieArray) {
// 把遍历出来的转成数组split("=")
// 用结构赋值的方式从里面的每一项里面找到我们想要的
[cookieName, cookieValue] = item.split("=");
// name是属性值,需要自己加,比如,"sex","username" "age"
// cookieName===name,找到了属性名,意思就是我们找到了我们想要的内容
if (cookieName === name) {
return decodeURIComponent(cookieValue);
}
}
};
// 删除cookie
const removeCookie = (name) => {
// 当执行removeCookie的时候,就调用setCookie方法
// 删除和写入,里面的参数是一样的,只是删除的时候,要把 maxAge的值写成0
setCookie(name,"",0)
};
export { setCookie, getCookie, removeCookie };
HTML代码如下 引入封装好的cookie import{}
<!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>Document</title>
<style>
table {
margin: 0 auto;
}
.green {
background: green;
color: #fff;
border: none;
margin-right: 10px;
margin-top: 10px;
cursor: pointer;
}
.red {
margin-top: 10px;
cursor: pointer;
border: none;
color: #fff;
background-color: red;
}
</style>
</head>
<body>
<form action="#" method="get">
<table>
<tr>
<td>用户名</td>
<td>
<input
id="input"
name="username"
type="text"
placeholder="请输入用户名"
/>
</td>
</tr>
<tr>
<td><button id="btn1" class="green">登录</button></td>
<td><button id="btn2" class="red">删除</button></td>
</tr>
</table>
</form>
</body>
<script type="module">
// 点击按钮的时候,需要获取到cookie
import { setCookie, getCookie, removeCookie } from "./cookie.js";
const button1 = document.querySelector("button:nth-of-type(1)");
const button2 = document.getElementById("btn2");
const input = document.getElementById("input");
// 如果在点击登录之前,cookie里面有值,(也就是能获取到cookie的值)就把这个值传到input框里面
if (getCookie("username")) {
input.value = getCookie("username");
}
button1.onclick = function (e) {
e.preventDefault();
// 点击登录的时候,找到input里面的值
const username = input.value;
// 如果input框里面有值,就把值传到setCookie里面作为value
if (username) {
setCookie("username", username, 7 * 24 * 3600);
}
};
button2.onclick = function (e) {
e.preventDefault();
// 要删除的是setCookie里面传入的属性名
removeCookie("username");
// 点击了删除,原来input框里面的值就没有了
input.value = "";
};
</script>
</html>