cookies增删改擦操作

//判断是否存在名为aaa的cookie

function hasSetCookie(name){
    var strCookie = document.cookie;
    var arrCookie = strCookie.split("; ");
    for (var i = 0; i < arrCookie.length; i++) {
        var arr = arrCookie[i].split("=");
        if (arr[0] == name) {
            return true;
        }
    };
    return false;
}


//添加cookie  判断是否设置过期时间,expiresHours=0代表关闭浏览器时失效
function addCookie(name, value, expiresHours) {
    var cookieString = name + "=" + escape(value); //escape() 函数可对字符串进行编码,这样就可以在所有的计算机上读取该字符串。
    
    if (expiresHours > 0) {
        var date = new Date();
        date.setTime(date.getTime() + expiresHours *3600* 1000);
        cookieString = cookieString + ";expires=" + date.toUTCString();
    }
    document.cookie = cookieString;
}


//修改cookie  判断是否设置过期时间,expiresHours=0代表关闭浏览器时失效
function editCookie(name, value, expiresHours) {
    var cookieString = name + "=" + escape(value); //escape() 函数可对字符串进行编码,这样就可以在所有的计算机上读取该字符串。
    
    if (expiresHours > 0) {
        var date = new Date();
        date.setTime(date.getTime() + expiresHours *3600* 1000);
        cookieString = cookieString + ";expires=" + date.toUTCString();
    }
    document.cookie = cookieString;
}


//根据名字获取cookie的值
function getCookie(name) {
    var strCookie = document.cookie;
    var arrCookie = strCookie.split("; ");
    for (var i = 0; i < arrCookie.length; i++) {
        var arr = arrCookie[i].split("=");
        if (arr[0] == name) {
            return unescape(arr[1]);
            break;
        } else {
            continue;
        };
    };
}


//删除cookie
function deleteCookie(name){ 
    var date=new Date(); 
    date.setTime(date.getTime()-10000); 
    document.cookie=name+"=v; expires="+date.toUTCString(); 
} 

  

posted @ 2017-12-20 11:19  坏小子1993  阅读(188)  评论(0编辑  收藏  举报