Created
April 2, 2018 03:33
-
-
Save WinfredZhuwenfeng/eef79b018d076b694818a9a63490d7f5 to your computer and use it in GitHub Desktop.
封装cookie的添加,删除,查询方法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CookieUtil={ | |
addCookie:function(key,value,options){ | |
var str=key+"="+escape(value); | |
if(options.expires){ | |
var curr=new Date(); //options.expires的单位是小时 | |
curr.setTime(curr.getTime()+options.expires*3600*1000); | |
options.expires=curr.toGMTString(); | |
} | |
for(var k in options){ //有可能指定了cookie的path,cookie的domain | |
str+=";"+k+"="+options[k]; | |
} | |
document.cookie=str; | |
}, | |
queryCookie:function(key){ | |
var cookies=document.cookie; | |
//获得浏览器端存储的cookie,格式是key=value;key=value;key=value | |
cookies+=";"; | |
var start=cookies.indexOf(key); | |
if(start<=-1){ return null; } //说明不存在该cookie | |
var end=cookies.indexOf(";",start); | |
var value=cookies.slice(start+key.length+1,end); | |
return unescape(value); | |
}, | |
deleteCookie:function(key){ | |
var value=CookieUtil.queryCookie(key); | |
if(value===null){return false;} | |
CookieUtil.addCookie(key,value,{expires:0});//把过期时间设置为0,浏览器会马上自动帮我们删除cookie | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment