设置cookie


function setCookie(name,value,key){
    var Days = 1;
    var exp = new Date();
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
    if (key == null || key == "") {
        document.cookie = name + "=" + encodeURI(value) + ";expires=" + exp.toGMTString()+";path=/";
    }
    else {
        var nameValue = getCookie(name);
        if (nameValue == "") {
            document.cookie = name + "=" + key + "=" + encodeURI(value) + ";expires=" + exp.toGMTString() + ";path=/";
        }
        else {
            var keyValue = getCookie(name, key);
            if (keyValue != "") {
                nameValue = nameValue.replace(key + "=" + keyValue, key + "=" +encodeURI ( value));
                document.cookie = name + "=" + nameValue + ";expires=" + exp.toGMTString() + ";path=/";
            }
            else {
                document.cookie = name + "=" + nameValue + "&" + key + "=" + encodeURI(value) + ";expires=" + exp.toGMTString() + ";path=/";
            }
        }
    }
}


取cookie

function getCookie(key){
    var arr1=document.cookie.split("; ");//由于cookie是通过一个分号+空格的形式串联起来的,所以这里需要先按分号空格截断,变成[name=Jack,pwd=123456,age=22]数组类型;
    for(var i=0;i<arr1.length;i++){
        var arr2=arr1[i].split("=");//通过=截断,把name=Jack截断成[name,Jack]数组;
        if(arr2[0]==key){
            return decodeURI(arr2[1]);
        }
    }
}