Cookie新增、獲取以及刪除操作

冰山上的來客_胡楊發表於2018-06-20
/**
 * 新增cookie值
 */
function setCookie (name, value) {  
    document.cookie = name + "=" + escape(value); 
} 
 
/**
 * 根據cookie名,取得cookie值
 */ 
function getCookie(name) {   
    var search;  
    search = name + "=" 
    offset = document.cookie.indexOf(search) 
    if (offset != -1) { 
        offset += search.length ; 
        end = document.cookie.indexOf(";", offset) ; 
        if (end == -1) {
            end = document.cookie.length;
        }
        return unescape(document.cookie.substring(offset, end)); 
    } else {
        return "";
    } 
    
} 

/**
 * 刪除某一cookie 
 */
function deleteCookie(name) {
    //此 cookie 將被儲存 30 天
    var Days = 30;
    var expdate = new Date(); 
    expdate.setTime(expdate.getTime() - (Days*24*60*60*1000)); 
    setCookie(name, "", expdate); 
}

相關文章