首页 > 代码库 > JS设置cookie,删除cookie
JS设置cookie,删除cookie
js设置cookie有很多种方法。
第一种:(这个是w3c官网的代码)
<script>//设置cookiefunction 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;}//获取cookiefunction 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方法!//写cookiesfunction 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()); } //读取cookiesfunction getCookie(name){ var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)"); if(arr=document.cookie.match(reg)) return (arr[2]); else return null;}//删除cookiesfunction 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>
JS设置cookie,删除cookie
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。