<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title>JS Cookie的操作</title>
<script>
//设置 cookie 值的函数
function setCookie(cname,cvalue,exdays){
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
//获取 cookie 值的函数
function getCookie(cname){
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
//删除 cookie 值的函数
function delCookie(cname){
document.cookie = cname+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
//检测 cookie 值的函数
function checkCookie(){
var user=getCookie("username");
if (user!=""){
alert("获取 cookie:" + user);
}else{
user = prompt("设置 cookie:","");
if (user!="" && user!=null){
setCookie("username",user,30);
}
}
}
</script>
</head>
<body οnlοad="checkCookie()">
<div οnclick="delCookie('username');">删除Cookie</div>
</body>
</html>
标签:cookie,expires,JS,cname,Cookie,var,操作 From: https://blog.51cto.com/u_16171388/6558681