JS cookie封装

蹦蹦豆

蹦蹦豆

发表于 2017-01-10 16:36:46
内容来源: 网络
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <style>
        #cas{
            display: block;
            border:1px solid;
            margin:auto;
        }
    </style>
    <title>操控字体的数据</title>
</head>
<body>
    <div >
        <img src="/photos/touxiang.jpg" />
        <img id='hgk' src="/photos/canvas.png" />
    </div>
    <script>
    var Ecookie=function(){
        this.doc=document;
    }
    Ecookie.prototype={
        constructor:Ecookie,
        set:function(name,val,day){
            var name=encodeURIComponent(name),
                val=encodeURIComponent(val),
                Days = day,
                exp = new Date(); 
            if(Days==-1){
                exp.setTime(new Date(0)); 
            }else{
                exp.setTime(exp.getTime() + Days*24*60*60*1000); 
            }
            console.log(exp.toGMTString());
            this.doc.cookie = name + "="+ val + ";expires=" + exp.toGMTString();
        },
        get:function(name){
            var name=encodeURIComponent(name)+"=",
                start=this.doc.cookie.indexOf(name),
                cookieVal=null;
            if(start>-1){
                var end=this.doc.cookie.indexOf(";",start);
                if(end==-1){
                    end=this.doc.cookie.length;
                }
                cookieVal=decodeURIComponent(this.doc.cookie.substring(start+name.length,end))
            }
            return cookieVal;

        },
        del:function(name){
            this.set(name,'',-1)
        }
    }
    var ecookie=new Ecookie();
    ecookie.set('name','小寒',7);
    // ecookie.del('name');
    console.log(ecookie.get('name'));
    </script>
</body>
</html>

内容来源:https://segmentfault.com/a/1190000008061224

相关帖子
用户评论
开源开发学习小组列表