设置cookie
function setCookie(name,value,expires) { var exp = new Date(); exp.setTime(exp.getTime() + expires*1000); document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString(); } 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 + "=" + escape(cvalue) + "; " + expires; }
获取cookie
function getCookie(name) { var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)")); if(arr != null) return unescape(arr[2]); return false; } 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
删除 cookie 非常简单。您只需要设置 expires 参数为以前的时间即可
document.cookie='firstname=John;expires=Thu, 01 Jan 1970 00:00:00 GMT'