今天下午比较闲,随便做了一个cookie的封装

转载 (原文地址) jiushini50 随笔 待整理 497阅读 2014-08-27 16:00:13 举报

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>封装Cookie</title>
</head>

<body>

<script type="text/javascript">
var cookie=function(iTime){
this.iTime=iTime;

this.init=function(){//初始化
    if(this.iTime=='' || this.iTime=='undefined'){
        this.iTime=30;
    }
}

this.setCookie=function(obj){//设置cookie
    var txt="";
    var time=new Date();
    time.setDate(time.getDate()+this.iTime*60*1000);
    for(var p in obj){
        document.cookie=p+"="+obj[p];
    }
    document.cookie='expires='+time.toGMTString();
}

this.getCookie=function(name){//获取cookie
    var arr=document.cookie.split(';');
    for(var i=0;i<arr.length;i++){
        var arr2=this.trim(arr[i]).split('=');

        if(arr2[0]==name){
            return arr2[1];
        }
    }
    return '';
}

this.delCookie=function(name){//删除cookie
     this.setCookie(name,1,-1);
}

this.trim=function(str){
    return str.replace(/(^\s*)|(\s*$)/g, ""); 
}

}

var usercookie=new cookie(10);
var cjson={
'userid' : '11',
'username' : 'admin'
};

usercookie.setCookie(cjson)
alert(usercookie.getCookie("username"));
</script>

</body>
</html>

评论 ( 0 )
最新评论
暂无评论

赶紧努力消灭 0 回复