js封装cookie的操作

var cookie = {
    /**
     * 设置cookie
     * @param key cookie名
     * @param value cookie值
     * @param expires 失效时间
     * @param path 路径
     * @param domain 域名
     * @param isSecure 是否进行安全设置
     */
    setCookie : function(key,value,expires,path,domain,isSecure){
        //获取多个cookie值用&连接的,或只是获取name的value值
        var str=encodeURIComponent(key)+"="+encodeURIComponent(value);
        //获取一个cookie值
        //var str=key+"="+value;
        if(typeof expires == "number"){
            var date = new Date();
            date.setDate(date.getDate() + expires);
            str+=";expires="+date;
        }
        if(path){
            str+=";path="+path;
        }
        if(domain){
            str+=";domain="+domain;
        }
        if(isSecure){
            str+=";secure";
        }
        document.cookie= str;
    },
    //清除cookie
    removeCookie : function(key) {
        //此时this代表cookie对象
        this.setCookie(key,"",-1);
    },
    //获取cookie的value值
    getCookie: function(key){
        var str = document.cookie;
        var arr = str.split("; ");
        for(var i = 0;i < arr.length;i++){
            if(arr[i].indexOf(key) != -1){
                var temp = arr[i].split("=");
                if(temp[0] == key){
                    return decodeURIComponent(temp[1]);
                }
            }
        }
        return null;
    },
    //获取cookie的value值
    getCookieFromMulti : function(key1,key2){
        var strValue = cookie.getCookie(key1);
        if(!strValue){
            return null;
        }
        var arrValue = strValue.split("&");
        if(!key2){
            return arrValue[0];
        }
        for(var i = 0;i < arrValue.length;i++){
            if(arrValue[i].indexOf(key2) != -1){
                var tempValue = arrValue[i].split("=");
                if(tempValue[0] == key2){
                    return decodeURIComponent(tempValue[1]);
                }
            }


        }
        return null;
    },
    //改变cookie中任意变量的值
    setCookieAtMulti : function(key1,key2,value){
        var vals = this.getCookie(key1);
        var arrValList = vals.split("&");
        for(var i = 0; i < arrValList.length; i++){
            if(arrValList[i].indexOf(key2) != -1){
                var temp = arrValList[i].split("=");
                if(temp[0] == key2){
                    arrValList[i] = key2 + "=" + value;
                    var vals = arrValList.join("&");
                    this.setCookie(key1,vals);
                    break;
                }
            }
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值