JS设置cookie,删除cookie
js设置cookie有很多种方法。
第一种:(这个是w3c官网的代码)
<script> //设置cookie function setCookie(cname, cvalue, exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays*24*60*60*1000)); var expires = "expires="+d.toUTCString(); 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]; while (c.charAt(0)==‘ ‘) c = c.substring(1); if (c.indexOf(name) != -1) return c.substring(name.length, c.length); } return ""; } //清除cookie function clearCookie(name) { setCookie(name, "", -1); } function checkCookie() { var user = getCookie("username"); if (user != "") { alert("Welcome again " + user); } else { user = prompt("Please enter your name:", ""); if (user != "" && user != null) { setCookie("username", user, 365); } } } checkCookie(); </script>
第二种:
<script> //JS操作cookies方法! //写cookies function setCookie(c_name, value, expiredays){ var exdate=new Date(); exdate.setDate(exdate.getDate() + expiredays); document.cookie=c_name+ "=" + escape(value) + ((expiredays==null) ? "" : ";expires="+exdate.toGMTString()); } //读取cookies function getCookie(name) { var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)"); if(arr=document.cookie.match(reg)) return (arr[2]); else return null; } //删除cookies function delCookie(name) { var exp = new Date(); exp.setTime(exp.getTime() - 1); var cval=getCookie(name); if(cval!=null) document.cookie= name + "="+cval+";expires="+exp.toGMTString(); } //使用示例 setCookie(‘username‘,‘Darren‘,30) alert(getCookie("username")); </script>
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。