原创

js中Cookie的简单使用

//添加一个cookie  
//name : cookie的key;value:值;expiresDays:保留几天,到期后会自动清除  
function addCookie(name,value,expiresDays){  
    var cookieString=name+"="+escape(value);  
    //判断是否设置过期时间  
    if(expiresDays>0){  
        var date=new Date();  
        date.setTime(date.getTime()+expiresDays*24*3600*1000);  
        cookieString=cookieString+";path=/;expires="+date.toGMTString()+";";  
    }  
    document.cookie=cookieString;  
}  


//获取指定名称的cookie值  
//name:添加时的key  
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 arr[1];  
        }  
    }  
    return "";  
}

  

//根据名称删除指定cookie  
function deleteCookie(name){  
    var date=new Date();  
    //只需将expires设置为当前时间之前即会销毁该cookie  
    date.setTime(date.getTime()-10000);  
    document.cookie=name+"=v; expires="+date.toGMTString();  
} 


正文到此结束