Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>cookie</title>
</head>
<body>
    <script type="text/javascript">
    setCookie("test","你是谁?",1);
    console.log(getCookie("test"));
    setTimeout(function(){
        removeCookie("test");
    },10000)
    setTimeout(function(){
        console.log(getCookie("test"));
    },11000)
    //设置cookie
    function setCookie(name,value,d){
        var dateo=new Date(),//获取当前时间对象
            day=dateo.getDate();//获取当前的日期-1值
        dateo.setDate(day+d);//修改当前值为d天后
        document.cookie=name+"="+encodeURI(value)+"; expires="+dateo.toGMTString();//设置cookie,expires为过期日期,设置的格式应该是"name=value; expires=过期日期"
    }
    
    //获取cookie
    function getCookie(name){
        var cookiestr=document.cookie,//获取cookie,格式应该为"name=value; name0=value0"
            cookiearr0=cookiestr.split("; "),//以"; "来分构字符串成数组 ["name=value","name0=value0"]
            cookiearr1=[];
        for(var i=0;i<cookiearr0.length;i++){
            cookiearr1=cookiearr0[i].split("=");//以"="分构字符串为数组,["name","value"]
            if(cookiearr1[0]==name){//如果找到相同名称的cookie,返回它的值
                return decodeURI(cookiearr1[1]);
            }
        }
        return "";//如果没有找到相同名的cookir,返回空
    }
    //删除cookie
    function removeCookie(name){
        setCookie(name,"",-1);//把过期时间设为昨天,即删除了当前cookie
    }
    </script>
</body>
</html>
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
anonymouspro
0viewers