JavaScript设置、获取、清除单值和多值cookie的方法

(编辑:jimmy 日期: 2024/10/5 浏览:2)

废话不多说了,直接给大家贴代码了。

具体代码如下:

var CookieUtil = (function () {
   var Cookie = function () {
     // 获取单值cookie
     this.get = function(name) {
       var start = document.cookie.indexOf(encodeURIComponent(name)) ;
       var end = document.cookie.indexOf(';', start) ;
       if(end == -) {
         end = document.cookie.length;
       }
       return decodeURIComponent(document.cookie.substring(start+name.length+,end));
     };
     // 设置单值cookie
     this.set = function(name, value, expires, path, domain, secure) {
       var cookieText = encodeURIComponent(name) + "=" + encodeURIComponent(value);
       // 设置默认过期时间为七天
       if(expires == undefined) {
         var date = new Date();
         date.setTime(date.getTime() + ****);
         expires = date ;
       }
       if(expires instanceof Date) {
         cookieText += "; expires=" + expires.toGMTString();
       }
       if(path != undefined) {
         cookieText += "; path=" + path;
       }
       if(domain != undefined) {
         cookieText += "; domain" + domain;
       }
       if(secure != undefined) {
         cookieText += "; secure";
       }
       document.cookie = cookieText;
     };
     // 清除单值cookie
     this.unset = function(name, path, domain, secure) {
       this.set(name, '', new Date(), path, domain, secure );
     };
     // 设置多值cookie
     this.setAll = function(name, subCookies, expires, path, domain, secure) {
       var cookieText = ";" + encodeURIComponent(name) + "=",
       arr = new Array();
       for(var attr in subCookies) {
         arr.push([encodeURIComponent(attr)] + ":" + encodeURIComponent(subCookies[attr]));
       } 
       this.set(name, arr.join('&'), expires, path, domain, secure);
     };
     // 获取多值cookie
     this.getAll = function(name) {
       var obj = {};
       var arr = this.get(name).split('&');
       for(var i = , len = arr.length; i < len; i++) {
         var tmpArr = arr[i].split(':');
         obj[decodeURIComponent(tmpArr[])] = decodeURIComponent(tmpArr[]);
       }
       return obj;
     };
     // 获取多值cookie的子cookie
     this.getSub = function(name, subname) {
       var obj = this.getAll(name);
       return obj[subname];
     };
     // 清除指定的多值cookie
     this.unsetAll = function(name,path,domain,secure) {
       this.unset(name, '', new Date(), path, domain, secure);
     };
     // 清除指定多值cookie的子cookie
     this.unsetSub = function(name, subname,path, domain, secure) {
       var obj = this.getAll(name);
       delete obj[subname];
       this.setAll(name, obj, null, path, domain, secure);
     };
   };
   return new Cookie();
 })();

 以上代码就是本文给大家介绍JavaScript设置、获取、清除单值和多值cookie的方法,有哪里不清楚的地方欢迎给我留言。

一句话新闻

微软与英特尔等合作伙伴联合定义“AI PC”:键盘需配有Copilot物理按键
几个月来,英特尔、微软、AMD和其它厂商都在共同推动“AI PC”的想法,朝着更多的AI功能迈进。在近日,英特尔在台北举行的开发者活动中,也宣布了关于AI PC加速计划、新的PC开发者计划和独立硬件供应商计划。
在此次发布会上,英特尔还发布了全新的全新的酷睿Ultra Meteor Lake NUC开发套件,以及联合微软等合作伙伴联合定义“AI PC”的定义标准。