我们可以单独写一个js脚本,定义一个对象。
分为两种情况,一种是写,一种是读。代码实现如下:
var Cookie = {
set: function (key, value, exdays) {
let exdate = new Date() // 获取时间
exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays) // 保存的天数
// 字符串拼接cookie
// eslint-disable-next-line camelcase
window.document.cookie = key + '=' + value + ';path=/;expires=' + exdate.toGMTString()
},
get: function (key) {
if (document.cookie.length > 0) {
var arr = document.cookie.split('; ') // 这里显示的格式需要切割一下自己可输出看下
for (let i = 0; i < arr.length; i++) {
let arr2 = arr[i].split('=') // 再次切割
// 判断查找相对应的值
if (arr2[0] === key) {
return arr2[1]
}
}
}
},
remove: function (key) {
set(key, '', -1);
}
};
最后的remove则是我们删除cookie。
在某个项目的登录界面<script>标签中,使用如下:
if($("#rememberme").is(":checked")){
Cookie.set("username.com",username,100);//表示保存100天
Cookie.set("password.com",password,100)
}else {
Cookie.set("username.com","",-1);//表示删除cookie
Cookie.set("password.com","",-1)
}
如果有用的话,点个赞吧。