設定cookie和查詢cookie的方法

kimingw發表於2017-03-21

1、設定cookie(名稱,值,過期時間)

function setCookie(key,value,d){
    if(d === undefined){
        document.cookie = encodeURIComponent(key) + "=" + encodeURIComponent(value);
    }else{
        document.cookie = encodeURIComponent(key) + "=" + encodeURIComponent(value) + ";max-age=" + (d*60*60*24);        
    }
}

2、查詢cookie(名稱)

function getCookie(key){
    var arr1 = document.cookie.split("; ");
    for(var i = 0; i < arr1.length; i++){
        var arr2 = arr1[i].split("=");
        if(arr2[0] == key){
            return decodeURIComponent(arr2[1]);
        }
    }
}

  

相關文章