首页 > 代码库 > 封装cookie

封装cookie

function cookie(name,value,expires){        switch(typeof value){        case ‘string‘:    //设置            var exp=‘‘;            if(expires){                var oDate=new Date();                oDate.setDate(oDate.getDate()+expires);                exp=‘;expires=‘+oDate.toUTCString();            }            document.cookie=name+‘=‘+encodeURIComponent(value)+exp;            break;        case ‘undefined‘:    //获取            if(document.cookie){                var arr=document.cookie.split(‘; ‘),                    aLen=arr.length,                    nLen=name.length;                for(var i=0; i<aLen; i++){                    if(arr[i].substring(0,nLen)==name){                        return decodeURIComponent(arr[i].substring(nLen+1));                    }                }            }            break;        default:    //删除            arguments.callee(name,‘1‘,-1);    }    }

 

使用方法:

cookie(‘username‘,‘wei\n魏...‘,14);    //设置cookie,14天后cookie删除cookie(‘username‘,‘wei‘);    //设置cookie,浏览器关闭时cookie删除cookie(‘age‘,‘21‘);    //设置cookie,注意用引号把数字变成字符串cookie(‘username‘);    //获取cookiecookie(‘username‘,null);    //删除cookie

 

封装cookie