js cookie添加,读取,删除


<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>js cookie添加,读取,删除</title>

<script>

function setCookie(name, value, days){
    if(null==days){
        days=1;
    }
    var datex = new Date();
    datex.setHours(datex.getHours()+24*days+8);
    var ex=";expires="+datex.toUTCString();
    document.cookie=name+"="+value+ex;
} 

function getCookie(name){
    var a=document.cookie.split(";");
    console.log(a);
    for(var i=0;i<a.length;i++){
        if(-1!=a[i].indexOf(name)){
            return a[i].replace(' ','').replace(name+'=','');
        }
    }
    return null;
}


function getAllCookies(){
    console.log(document.cookie);
}
function delCookie5MinutesLater(){
    var text1=document.getElementById('text1');
    delCookie(text1.value);
    console.log(document.cookie);
}
function addCookie(){
    var text2=document.getElementById('text2');
    var text3=document.getElementById('text3');
    setCookie(text2.value, text3.value, 7);
    console.log(document.cookie);
}

function delCookie(name){
    var datex = new Date();
    datex.setSeconds(datex.getSeconds()+5);
    var ex=";expires="+datex.toUTCString();
    document.cookie=name+"=willBeDel5MinutesLater"+ex;
} 

console.log(document.cookie);
</script>



需要添加的cookie名
<input type="text" id="text2" size="5" />
cookie值
<input type="text" id="text3" size="5" />
<input value="添加新cookie" onclick="addCookie()" type="button" />
<hr />



需要删除的cookie名
<input type="text" id="text1" size="5" />
<input value="点击这里5秒后会删除这个cookie" onclick="delCookie5MinutesLater()" type="button" />
<hr />



<input value="读取当前所有cookie" onclick="getAllCookies()" type="button" />

程序运行结果如下,点击这里亲自运行看看