写一个js控制cookie的代码
时间: 2023-02-10 19:41:14 浏览: 116
js控制的cookie
下面是一个示例代码,可以用来控制 cookie。
```
// 设置 cookie
function setCookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
// 获取 cookie
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
// 删除 cookie
function deleteCookie(name) {
setCookie(name, "", -1);
}
```
使用方法:
```
// 设置 cookie,默认保存 30 天
setCookie("username", "John", 30);
// 获取 cookie
var username = getCookie("username");
// 删除 cookie
deleteCookie("username");
```
阅读全文