cookie的创建、获取、删除

let $ = {
    cookie(key, value, json) {
        //初始化json参数必须为对象
        json = json || {};
        //链接主键值对
        let cookie_str = encodeURIComponent(key) + '=' + encodeURIComponent(value);
        //判断是否有有效期
        if (!isNaN(json.expires)) {
            let date = new Date();
            date.setDate(date.getDate() + json.expires);
            cookie_str += ';expires=' + date;
        }
        //判断是否修改路径
        if (json.path) {
            cookie_str += ';path=' + json.path;
        }
        //判断是否指定域名
        if (json.domain) {
            cookie_str += ';domain=' + json.domain;
        }
        //判断是否安全
        if (json.secure) {
            cookie_str += ';secure';
        }
        //创建cookie
        document.cookie = cookie_str;
    },
    getCookie(key) {
        //以'; '进行切割成数组
        let arr = document.cookie.split('; ');
        for (let i = 0; i < arr.length; i++) {
            //以'='进行切割成数组
            let list = arr[i].split('=');
            //判断第一个元素的key,如果key相等,返回第二个元素的value
            if (encodeURIComponent(key) === list[0]) {
                return decodeURIComponent(list[1]);
            }
        }
    },
    removeCookie(key, json) {
        json = json || {};
        if (json.path) { //删除带有路径的cookie
            document.cookie = encodeURIComponent(key) + '=;expires=' + new Date(0) + ';path=' + json.path;
        } else { //删除默认路径的cookie
            document.cookie = encodeURIComponent(key) + '=;expires=' + new Date(0);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值