【教程】使用原生JS封装存储cookie

原创 萧瑟  2017-04-10 14:58:50  阅读 556 次 评论 0 条

JS下载地址

高速下载

代码展示

//设置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;
}
//获取cookie值

function getCookie(name) {
    var cookieName = encodeURIComponent(name) + '=';
    var cookieValue = decodeURIComponent(document.cookie.split(';')[0].split('=')[1]);
    return cookieValue;
}
//设置过期时间
function setCookieDate(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;
}
本文地址:https://www.xsyrz.cn/JS-cookie.html
版权声明:本文为原创文章,版权归 萧瑟 所有,欢迎分享本文,转载请保留出处!

发表评论


表情

还没有留言,还不快点抢沙发?