JS 操作 Cookie
程序员文章站
2022-12-19 21:59:58
获取 Cookie: 设置 Cookie: 删除 Cookie: ......
获取 Cookie:
/** * 获取 Cookie * @param {String} name Cookie 名称 */ function getCookie (name) { var reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)"); var arr = document.cookie.match(reg) if (arr) { return (arr[2]); } return null; };
设置 Cookie:
/** * 设置 Cookie * @param {String} name Cookie 名称 * @param {String} value Cookie 值 * @param {Number} exdays Cookie 过期时间 */ function setCookie (name, value, exdays) { var dateNow = new Date(); dateNow.setTime(dateNow.getTime() + (exdays * 24 * 60 * 60 * 1000)); var expires = 'expires=' + d.toUTCString(); document.cookie = name + '=' + value + '; ' + expires; };
删除 Cookie:
/** * 删除 Cookie * @param {String} name Cookie 名称 */ function delCookie (name) { var dateNow = new Date(); dateNow.setTime(dateNow.getTime() - 1); var currentCookie = getCookie(name); if (currentCookie != null) { document.cookie = name + "=" + currentCookie + ";expires=" + dateNow.toGMTString(); } };
上一篇: 第二届吴文俊人工智能科学技术奖在杭州揭晓