一个js cookie操作类

本文深入解析JavaScript中Cookie的创建、获取、设置生命周期、删除及所有属性的使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用例:

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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值