cookie的设置、获取和删除封装

在我们为了去完成数据储存,有时会用到cookie,简单封装一下cookie:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
<script type="text/javascript">
    //设置cookie
    function setCookie(name,value,days){
        days=days?days:30;//一个月后失效
        var exp=new Date();
        exp.setTime(exp*1+days*24*60*60*1000);
        document.cookie=name+"="+escape(value)+";expires="+exp;
    }
    setCookie("tel","13546",10);
    setCookie("name","arch",1);
    console.log(document.cookie);

    //获取cookie
    function getCookie(name){
        var reg=new RegExp('(^| )'+name+'=([^;]*)(;|$)');
        var arr=document.cookie.match(reg);
        if(arr) return arr[2];
        return null;
    }
    getCookie("name");
    console.log(getCookie("name"));

    //删除cookie
    function delCookie(name){
        if(getCookie(name)){
            setCookie(name,"",-1);
        }
    }
    delCookie("tel");
</script>
</body>
</html>

 

posted @ 2016-01-30 09:38  Shoestrong  阅读(229)  评论(0)    收藏  举报
更多精彩请访问个人主页http://shoestrong.cc