JS学习笔记——cookie缓存

今天学习了下cookie的用法 , 简单做了个小封装


/*封装cookie*/
function setCookie(name,value,expires,path,domain,secure) {
    var cookieName = encodeURIComponent(name)+'='+encodeURIComponent(value);
    if(expires instanceof Date){
        cookieName += ';expires' + expires;
    }
    if(path){
        cookieName += ';path' + path;
    }
    if(domain){
        cookieName += ';domain' + domain;
    }
    if(secure){
        cookieName += ';secure';
    }
    document.cookie = cookieName;
}

/*设置有效时间*/
function setCookieData(day) {
    var date = null;
    if( typeof day == 'number'&& day > 0) {
        date = new Date();
        date.setDate(date.getDate() + day);
    }else {
        throw new Error('您传递的天数不合适,应为大于0的数字')
    }
    return date;
}
/*获取cookie*/
function getCookie(name) {
    var cookieName = encodeURIComponent(name)+ "=";                 //得到cookie的名
    var cookieStart = document.cookie.indexOf(cookieName);          //得到cookie名的起始位置
    if(cookieStart>-1){
        var cookieEnd = document.cookie.indexOf(';',cookieStart);   //从cookie名的起始位置查找分号
        if(cookieEnd == -1){                            //表示最后一个cookie
            cookieEnd = document.cookie.length;
        }

        var cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length,cookieEnd));
    }
    return cookieValue;
}

setCookie('user','aaa',setCookieData(2));
setCookie('email','[email protected]',setCookieData(2));

alert(getCookie('email'));

你可能感兴趣的:(JavaScript,web前端)