1

添加cookie的函数


    //后三个参数为可选项
    function addCookie(key,value,day,path,domin) {
        //1.处理保存的路径
            //找到html文件前的 / 索引
        var index = window.location.pathname.lastIndexOf("/");
        var currentIndex =            window.location.pathname.slice(0,index);
        path = path || currentIndex;
        //2.处理默认保存的domin(域名)
        domin = domin || document.domin;

        //3.处理输入的时间
        if (!day){
            document.cookie = key + "=" + value + ";path=" + path + ";domin=" + domin;
        }else {
            var date = new Date();
            date.setDate(date.getDate() + day);
            document.cookie = key + "=" + value + ";expires=" + date.toGMTString() + ";path=" + path + ";domin=" + domin;
        }
    }

获取cookie的函数

function getCookie(key) {
        //以分号分割cookie并返回一个数组
        var res = document.cookie.split(";");
        for (let i = 0; i < res.length; i++){
            var temp = res[i].split("=");
            if (temp[0].trim() === key) {
                return temp[1]
            }
        }
    }

删除cookie的函数

//对于cookie来说,如果expires即cookie过期时间为过去的值,那么浏览器会自动清除cookie
function delCookie(key) {
        addCookie(key,getCookie(key), -999)
}

WanGqD
15 声望0 粉丝