js获取cookie的封装类

一个优秀的js封装cookie类,开箱即用:

var Cookie = {
    set: function(key,value,expiresTime)
    {
        if(expiresTime)
        {
            var date = new Date();
            date.setTime(date.getTime()+expiresTime);
            var expiresStr = "expires="+date.toGMTString()+';';
        }else
        {
            var expiresStr='';
        }
        document.cookie = key+'='+escape(value)+';'+expiresStr;
    },
    get: function(key)
    {
        var getCookie = document.cookie.replace(/[ ]/g,'');
        var resArr = getCookie.split(';');
        var res;
        for(var i = 0,len = resArr;i < len;i++)
        {
            var arr = resArr[i].split('=');
            if(arr[0] == key)
            {
                res = arr[1];
                break;
            }
        }
        return unescape(res);
    }
};

 使用方法:

//设置cookie
Cookie.set(key,value,expiresTime)
//读取cookie
Cookie.get(key)

 

 
posted @ 2020-05-04 11:45  闻海南  阅读(108)  评论(0编辑  收藏