JS实现Cookie读、写、删除操作工具类示例
本文实例讲述了JS实现Cookie读、写、删除操作工具类。分享给大家供大家参考,具体如下:
/*** *读取指定的Cookie值readCookie("id"); *@param{string}cookieNameCookie名称 */ functionreadCookie(cookieName){ vartheCookie=""+document.cookie; varind=theCookie.indexOf(cookieName); if(ind==-1||cookieName=="")return""; varind1=theCookie.indexOf(';',ind); if(ind1==-1)ind1=theCookie.length; /*读取Cookie值*/ returnunescape(theCookie.substring(ind+cookieName.length+1,ind1)); } /*** *设置Cookie值setCookie("id",1); *@param{string}cookieNameCookie名称 *@param{string}cookieValueCookie值 *@param{number}nDaysCookie过期天数 */ functionsetCookie(cookieName,cookieValue){ /*当前日期*/ vartoday=newDate(); /*Cookie过期时间*/ varexpire=newDate(); /*如果未设置nDays参数或者nDays为0,取默认值1*/ //if(nDays==null||nDays==0)nDays=1; /*计算Cookie过期时间【3600000*24为一天】*/ expire.setTime(today.getTime()+400000);//5分钟 document.cookie=cookieName+"="+escape(cookieValue)+";expires="+expire.toGMTString(); } /*** *删除cookie中指定变量函数 *@param{string}$nameCookie名称 */ functiondeleteCookie($name){ varmyDate=newDate(); myDate.setTime(-1000);//设置时间 document.cookie=$name+"='';expires="+myDate.toGMTString(); } /*** *删除cookie中所有定变量函数 *@param{string}cookieNameCookie名称 *@param{string}cookieValueCookie值 *@param{number}nDaysCookie过期天数 */ functionclearCookie(){ varmyDate=newDate(); myDate.setTime(-1000);//设置时间 vardata=document.cookie; vardataArray=data.split(";"); for(vari=0;i附:JS操作cookie的小插件
varCookieUtil={ //设置cookie set:function(name,value,expires,domain,path,secure){ varcookieText=""; cookieText+=encodeURIComponent(name)+"="+encodeURIComponent(value); if(expiresinstanceofDate){ cookieText+=";expires="+expires.toGMTString(); } if(path){ cookieText+=";path="+path; } if(domain){ cookieText+=";domain="+domain; } if(secure){ cookieText+=";secure"; } document.cookie=cookieText; }, //name=value;expires=expiration_time;path=domain_path;domain=domain_name;secure //获取cookie get:function(name){ varcookieName=encodeURIComponent(name)+"=", cookieStart=document.cookie.indexOf(cookieName), cookieValue=""; if(cookieStart>-1){ varcookieEnd=document.cookie.indexOf(";",cookieStart); if(cookieEnd==-1){ cookieEnd=document.cookie.length; } cookieValue=decodeURIComponent(document.cookie.substring(cookieStart+cookieName.length,cookieEnd)); } returncookieValue; }, //删除cookie unset:function(name,domain,path,secure){ this.set(name,"",Date(0),domain,path,secure); } };更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》、《JavaScript查找算法技巧总结》、《JavaScript动画特效与技巧汇总》、《JavaScript错误与调试技巧总结》及《JavaScript数学运算用法总结》
希望本文所述对大家JavaScript程序设计有所帮助。