使用 jQuery 创建、读取和删除 cookie
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1599287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create, read, and erase cookies with jQuery
提问by Agus Puryanto
Somebody help me. How to create, read and erase some cookies with jQuery ?
来人帮帮我。如何使用 jQuery 创建、读取和删除一些 cookie?
回答by Ramesh Soni
Use COOKIE plugin:
使用COOKIE 插件:
Set a cookie
设置一个 cookie
$.cookie("example", "foo"); // Sample 1
$.cookie("example", "foo", { expires: 7 }); // Sample 2
$.cookie("example", "foo", { path: '/admin', expires: 7 }); // Sample 3
Get a cookie
得到一块饼干
alert( $.cookie("example") );
Delete the cookie
删除cookie
$.removeCookie("example");
回答by balexandre
As I know, there is no direct support, but you can use plain-ol' javascript for that:
据我所知,没有直接支持,但您可以使用普通 ol' javascript:
// Cookies
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = 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 c.substring(nameEQ.length, c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
回答by Natrium
Google is my friend and it showed me this page:
谷歌是我的朋友,它向我展示了这个页面:
回答by louis_coetzee
Use jquery cookie plugin, the link as working today: https://github.com/js-cookie/js-cookie
使用 jquery cookie 插件,链接为今天工作:https: //github.com/js-cookie/js-cookie