下面是我爱模板网整理的创建、获取、删除cookie的js函数,而且做好了自动转码功能,传递中文英文都没有任何问题,使用js cookie也变的如此简单:
//创建cookie,这里的expires失效时间,可以通过后面的setCookieDate设置好,然后传给expires function setCookie(name, value, expires, path, domain, secure) { var cookieText = encodeURIComponent(name) + '=' + encodeURIComponent(value); if (expires instanceof Date) { cookieText += '; expires=' + expires; } if (path) { cookieText += '; expires=' + expires; } if (domain) { cookieText += '; domain=' + domain; } if (secure) { cookieText += '; secure'; } document.cookie = cookieText; }
//获取cookie,只需要输入想要获取的cookie名称,即可得到对应的值: function getCookie(name) { var cookieName = encodeURIComponent(name) + '='; var cookieStart = document.cookie.indexOf(cookieName); var cookieValue = null; if (cookieStart > -1) { var cookieEnd = document.cookie.indexOf(';', cookieStart); if (cookieEnd == -1) { cookieEnd = document.cookie.length; } cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length, cookieEnd)); } return cookieValue; }
//删除cookie function unsetCookie(name) { document.cookie = name + "= ; expires=" + new Date(0); }
//失效天数,直接传一个天数即可 function setCookieDate(day) { if (typeof day == 'number' && day > 0) { var date = new Date(); date.setDate(date.getDate() + day); } else { throw new Error('传递的day必须是一个天数,必须比0大'); } return date; }本文转载自:合肥网站建设