cookie封装

//设置cookie
function setCookie(name,value,days){
    //如果不设置天数 , 默认为30天
    days=days?days:30;
    var exp=new Date();
    exp.setTime(exp*1+days*(24*60*60*1000));
    document.cookie=name+'='+escape(value)+';expires='+exp;
}
 
setCookie("marray","lili@sohu.com",1);
setCookie("num","123456",1);
setCookie("ok","myhello",1);
setCookie("my","我的",1);
 
//获取cookie
 
function getCookie(name){
    // document.cookie 获取所有的cookie 包括名称和值 类型为字符串
    var reg=new RegExp('(^| )'+name+'=([^;]*)(;|$)');
    var arr=document.cookie.match(reg);
    if(arr) return unescape(arr[2]);
    return null;
}
 
console.log(getCookie("marray"));
console.log(getCookie("num"));
console.log(getCookie("my"));
 
//删除cookie 
function delCokie(name){
    // 设置时间过期
    if(getCookie(name)){
        setCookie(name,"",-1);
    }
}
 
delCokie("marray");
delCokie("num");
delCokie("ok");
posted @ 2016-12-20 16:56  *小七儿*  阅读(165)  评论(0编辑  收藏  举报