- name: cookie 键名
- value:cookie 键值
- domain:哪些域名能访问到此cookie
- path:哪些路径能访问
- expires/max-age:过期时间
cookie 注意点
- document.cookie 不能同时设置多个 cookie 值
- document.cookie 获取到的是个字符串
简单封装
var manageCookies = {
set: function(key, value, expTime) {
document.cookie = key + '=' + value + ';max-age=' + expTime;
return this;
},
delete: function(key) {
return this.set(key, '', -1);
},
get: function(key, cb) {
// "name=lance; age=26"
var CookiesArray = document.cookie.split("; ");
for (var i = 0; i < CookiesArray.length; i++) {
var CookieItem = CookiesArray[i];
// ["name=lance", "age=26"]
var CookieItemArray = CookieItem.split("=");
if (CookieItemArray[0] === key) {
cb(CookieItemArray[1]);
return this;
}
}
cb(undefined);
return this;
}
}
manageCookies.set("name", "xiaoming", 10000)
.set("age", "20", 10000)
.delete("name")
.get("age", function(data) {
console.log(data);
});