js对cookie增删改查的封装

/**
 * 获取cookie
 * @param name
 * @returns {*}
 */
function getCookie(name) {
    var cookieArr = document.cookie.split("; ");//使用"; "分割Cookie
    var cva = [], temp;
    //循环的得到Cookie名称与值
    for (i = 0; i < cookieArr.length; i++) {
        temp = cookieArr[i].split("=");//用"="分割Cookie的名称与值
        cva[temp[0]] = unescape(temp[1]);
    }
    if (name) {
        //如果有name则输出这个name的Cookie值
        return cva[name];
    }
    else{
        //如果没有name则输出空数组
        return cva;
    }
}
/**
 * 保存cookie(保存时间为30天)
 * @param name
 * @param value
 */
function setCookie(name, value) {
    var Days = 30;
    var exp = new Date();
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";path=/";
}
/**
 * 删除cookie
 * @param name
 */
function delCookie(name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    if (cval != null){
        document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString() + ";path=/";
    }
}

 

posted @ 2018-10-15 13:46  样子2018  阅读(659)  评论(0编辑  收藏  举报