一个js cookie操作类

来源:互联网 发布:ag游戏平台源码 编辑:程序博客网 时间:2024/05/18 02:17

用例:

cookie = new cookie;

cookie.set('text1','123');

cookie.set('text2','321',3600*24);

text2 = cookie.get('text2');

cookie.del('text2');

cookie.setlifetime(3600*24*2);

cookie.set('text3','456');

alert(cookie.getall());


cookie.js——

var cookie = cookie || function(){

    cookies = document.cookie.split('; ');
    for (i in cookies){
        cookie = cookies[i].split('=');
        this.cookies[cookie[0]] = cookie[1];
    }
    this.date = new Date();//日期初始化
}
cookie.prototype = {
    cookies:[],//cookie值存储器
    lifetime:null,//生命周期存储器,单位毫秒
    date:null,//日期存储器
    setlifetime:function(lifetime){
        if (lifetime = parseInt(lifetime)){
            this.lifetime = lifetime;
        }
        return this;
    },
    get:function(name){
        if (this.cookies[name]){
            return this.cookies[name];
        }else{
            return false;
        }
    },
    getall:function(){
        return document.cookie;
    },
    set:function(name,value,lifetime){
        cookieText = name+'='+value+';';
        lifetime = lifetime || this.lifetime;
        if (lifetime = parseInt(lifetime)){
            this.date.setTime(this.date.getTime()+lifetime*1000);
            cookieText += 'expires='+this.date.toGMTString();
        }
        document.cookie = cookieText;
        return this;
    },
    del:function(name){
        if (this.cookies[name]){
            this.date.setTime(this.date.getTime()-10000);
            document.cookie = name+'=;expires='+this.date.toGMTString();
        }
        return this;
    }
};
原创粉丝点击