cookie的存取删
Posted Kevin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了cookie的存取删相关的知识,希望对你有一定的参考价值。
存: document.cookie = "name=Kevin;expires="+new Date().getDate()+7; //有效期7天 取: function GetCookie(sName) { var aCookie = document.cookie.split("; "); for (var i=0; i < aCookie.length; i++) { var aCrumb = aCookie[i].split("="); if (sName == aCrumb[0]) return unescape(aCrumb[1]); } return null; } GetCookie(‘name‘) //Kevin
//设置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();
以上是关于cookie的存取删的主要内容,如果未能解决你的问题,请参考以下文章
js代码片段: utils/lcoalStorage/cookie