javascript 操作cookie类

本文提供了一套使用JavaScript实现的Cookie操作方法,包括设置、获取和删除Cookie等功能,并支持设置Cookie的有效期、域名和路径等属性。此外还介绍了如何通过子键来管理和获取复合型Cookie值。

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

1 String.prototype.Trim = function()
2 {
3     return this.replace(/^/s+/g,"").replace(//s+$/g,"");
4 }
5
6 function JSCookie()
7 {
8     this.GetCookie = function(key)
9      {
10         var cookie = document.cookie;
11         var cookieArray = cookie.split(;);
12         var getvalue = "";
13         for(var i = 0;i<cookieArray.length;i++)
14          {
15             
16             if(cookieArray[i].Trim().substr(0,key.length) == key)
17              {
18                  getvalue = cookieArray[i].Trim().substr(key.length + 1);
19                 break;
20              }
21          }
22
23         return getvalue;
24      };
25     this.GetChild = function(cookiekey,childkey)
26      {
27         var child = this.GetCookie(cookiekey);
28         var childs = child.split(&);
29         var getvalue = "";
30         
31         for(var i = 0;i < childs.length;i++)
32          {
33             if(childs[i].Trim().substr(0,childkey.length) == childkey)
34              {
35                  getvalue = childs[i].Trim().substr(childkey.length + 1);
36                 break;
37              }
38          }
39         return getvalue;
40      };
41     this.SetCookie = function(key,value,expire,domain,path)
42      {
43         var cookie = "";
44         if(key != null && value != null)
45              cookie += key + "=" + value + ";";
46         if(expire != null)
47              cookie += "expires=" + expire.toGMTString() + ";";
48         if(domain != null)
49              cookie += "domain=" + domain + ";";
50         if(path != null)
51              cookie += "path=" + path + ";";
52          document.cookie = cookie;
53      };
54     this.Expire = function(key)
55      {
56          expire_time = new Date();
57          expire_time.setFullYear(expire_time.getFullYear() - 1);
58         var cookie = " " + key + "=e;expires=" + expire_time + ";"
59          document.cookie = cookie;
60      }
61 }


用法:
一、设置cookie
var cookie = new JSCookie();
//普通设置
cookie .SetCookie("key1","val1");

//过期时间为一年
var expire_time = new Date();
expire_time.setFullYear(expire_time.getFullYear() + 1);
cookie .SetCookie("key2","val2",expire_time);

//设置域及路径,带过期时间
cookie .SetCookie("key3","val3",expire_time,".cnblogs.com","/");

//设置带子键的cookie,子键分别是k1,k2,k3
cookie .SetCookie("key4","k1=1&k2=2&k3=3");

二、读取cookie
//简单获取
cookie .GetCookie("key1");
cookie .GetCookie("key2");
cookie .GetCookie("key3");
cookie .GetCookie("key4");
//获取key4的子键k1值
cookie .GetChild("key4","k1");

三、删除
cookie .Expire("key1");
cookie .Expire("key2");
cookie .Expire("key3");
cookie .Expire("key4");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值