前端JavaScript操作Cookie
阿新 • • 發佈:2018-12-06
<script type="application/javascript"> function getCookieByName(cookieName) { var cookieObj = {}; var cookieSplit=[]; // 以分號(;)分組 var cookieArr=document.cookie.split(";"); for(var i=0,len=cookieArr.length;i<len;i++) if(cookieArr[i]) { // 以等號(=)分組 cookieSplit=cookieArr[i].split("="); // Trim() 是自定義的函式,用來刪除字串兩邊的空格 cookieObj[cookieSplit[0].trim()]=cookieSplit[1].trim(); } return cookieObj[cookieName]; } function setCookie(key,value) { var date = new Date(), t = 5; date.setDate( date.getDate() + t ); document.cookie = key+'='+encodeURIComponent(value)+';expires='+date.toGMTString(); } function getCookieByKey(key) { var arr,reg = RegExp('(^| )'+key+'=([^;]+)(;|$)'); if (arr = document.cookie.match(reg)) //["username=liuwei;", "", "liuwei", ";"] return decodeURIComponent(arr[2]); else return null; } function delCookie(key) { var date = new Date(); date.setTime(date.getTime() - 1); var delValue = getCookie(key); if (!!delValue) { document.cookie = key+'='+delValue+';expires='+date.toGMTString(); } } </script>