cookie添加删除修改
//cookie添加 document.cookie="username=John Doe"; //添加过期时间 document.cookie="username1=John Doe1; expires=Thu, 18 Dec 2013 12:00:00 GMT"; //用 path 参数告诉浏览器 cookie 的路径。默认情况下,cookie 属于当前页面。 document.cookie="username2=John Doe2; expires=Thu, 18 Dec 2013 12:00:00 GMT; path=/"; //读取 Cookie var x = document.cookie; console.log(x); //修改 Cookie 也是创建新的覆盖旧的 //删除 Cookie 把期限设置成以前的时间 document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
//设置 cookie 值的函数 该函数设置了 cookie 名、cookie 值、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 checkCookie() { var username=getCookie("username"); if (username!="") { alert("Welcome again " + username); } else { username = prompt("Please enter your name:",""); if (username!="" && username!=null) { setCookie("username",username,365); } } }