js封装cookie
时间: 2023-09-30 09:04:38 浏览: 107
要封装 JavaScript 的 Cookie,可以创建一个名为 "CookieUtil" 的对象,并为该对象定义一些方法来处理 Cookie。以下是一个基本的示例:
```javascript
var CookieUtil = {
// 获取指定名称的 Cookie 值
get: function(name) {
var cookieName = encodeURIComponent(name) + "=",
cookieStart = document.cookie.indexOf(cookieName),
cookieValue = null;
if (cookieStart > -1) {
var cookieEnd = document.cookie.indexOf(";", cookieStart);
if (cookieEnd == -1) {
cookieEnd = document.cookie.length;
}
cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length, cookieEnd));
}
return cookieValue;
},
// 设置 Cookie
set: function(name, value, expires, path, domain, secure) {
var cookieText = encodeURIComponent(name) + "=" + encodeURIComponent(value);
if (expires instanceof Date) {
cookieText += "; expires=" + expires.toGMTString();
}
if (path) {
cookieText += "; path=" + path;
}
if (domain) {
cookieText += "; domain=" + domain;
}
if (secure) {
cookieText += "; secure";
}
document.cookie = cookieText;
},
// 删除指定名称的 Cookie
remove: function(name, path, domain, secure) {
this.set(name, "", new Date(0), path, domain, secure);
}
};
```
使用示例:
```javascript
// 设置一个名为 "username" 的 Cookie,有效期为一天
CookieUtil.set("username", "John Doe", new Date(Date.now() + (24 * 60 * 60 * 1000)));
// 获取名为 "username" 的 Cookie 值
var username = CookieUtil.get("username");
console.log(username);
// 删除名为 "username" 的 Cookie
CookieUtil.remove("username");
```
这只是一个简单的封装示例,你可以根据需要进行扩展和修改。
阅读全文