如何使用jQuery设置/取消设置cookie?如何使用jQuery设置和取消设置cookie,例如创建一个名为cookie并将test值设置为1?
4 回答
慕的地8271018
TA贡献1796条经验 获得超4个赞
没有必要特别使用jQuery来操作cookie。
从QuirksMode(包括转义字符)
function createCookie(name, value, days) { var expires; if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = "; expires=" + date.toGMTString(); } else { expires = ""; } document.cookie = encodeURIComponent(name) + "=" + encodeURIComponent(value) + expires + "; path=/";}function readCookie(name) { var nameEQ = encodeURIComponent(name) + "="; 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, c.length); if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length)); } return null;}function eraseCookie(name) { createCookie(name, "", -1);}
看一眼
忽然笑
TA贡献1806条经验 获得超5个赞
<script type="text/javascript"> function setCookie(key, value) { var expires = new Date(); expires.setTime(expires.getTime() + (1 * 24 * 60 * 60 * 1000)); document.cookie = key + '=' + value + ';expires=' + expires.toUTCString(); } function getCookie(key) { var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)'); return keyValue ? keyValue[2] : null; }</script>
您可以像设置cookie一样设置
setCookie('test','1');
你可以像这样获得cookies
getCookie('test');
希望它会对某人有所帮助:)
编辑:
如果你想单独为主页保存cookie的路径,那就这样做吧
function setCookie(key, value) { var expires = new Date(); expires.setTime(expires.getTime() + (1 * 24 * 60 * 60 * 1000)); document.cookie = key + '=' + value +';path=/'+ ';expires=' + expires.toUTCString(); }
添加回答
举报
0/150
提交
取消