Loading... JavaScript对Cookies的操作,JS对Cookie做增删改查。 ### 删除所有cookie ```js function clearAllCookie() { document.cookie.split(";").forEach(function (c) { document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/"); }); }; ``` ### 获取Cookie ```js function getCookie(cname) { var name = cname + "="; var decodedCookie = decodeURIComponent(document.cookie); var ca = decodedCookie.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) == 0) { return c.substring(name.length, c.length) } } return "" }; ``` ### 添加Cookie ```js function createCookie(name, value, days, path) { path = path || "/"; var expires = ""; if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = "; expires=" + date.toUTCString() } document.cookie = name + "=" + value + expires + "; path=" + path }; ``` ### 删除Cookie ```js function deleteCookie(name) { var expires = new Date(); expires.setTime(expires.getTime()-1); document.cookie = name + "=;expires=" + expires.toUTCString() }; ``` 最后修改:2022 年 05 月 31 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 如果觉得我的文章对你有用,请随意赞赏