2019 年 4 月更新
Cookie 的读取 / 操作不需要 jQuery,因此请不要使用下面的原始答案。
转到https://github.com/js-cookie/js-cookie ,然后在其中使用不依赖 jQuery 的库。
基本示例:
// Set a cookie
Cookies.set('name', 'value');
// Read the cookie
Cookies.get('name') => // => 'value'
有关详细信息,请参见 github 上的文档。
参见插件:
https://github.com/carhartl/jquery-cookie
然后,您可以执行以下操作:
$.cookie("test", 1);
删除:
$.removeCookie("test");
此外,要在 Cookie 上设置特定天数(此处为 10 天)的超时时间:
$.cookie("test", 1, { expires : 10 });
如果省略 expires 选项,则 cookie 成为会话 cookie,并在浏览器退出时被删除。
涵盖所有选项:
$.cookie("test", 1, {
expires : 10, // Expires in 10 days
path : '/', // The value of the path attribute of the cookie
// (Default: path of page that created the cookie).
domain : 'jquery.com', // The value of the domain attribute of the cookie
// (Default: domain of page that created the cookie).
secure : true // If set to true the secure attribute of the cookie
// will be set and the cookie transmission will
// require a secure protocol (defaults to false).
});
读取 cookie 的值:
var cookieValue = $.cookie("test");
如果 cookie 是在与当前路径不同的路径上创建的,则您可能希望指定 path 参数:
var cookieValue = $.cookie("test", { path: '/foo' });
更新(2015 年 4 月):
如下面的评论所述,使用原始插件的团队已删除了新项目( https://github.com/js-cookie/js-cookie )中的 jQuery 依赖项,该项目具有与相同的功能和通用语法 jQuery 版本。显然,原始插件没有任何用。
无需特别使用 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);
}
看一眼
<script type="text/javascript">
function setCookie(key, value, expiry) {
var expires = new Date();
expires.setTime(expires.getTime() + (expiry * 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;
}
function eraseCookie(key) {
var keyValue = getCookie(key);
setCookie(key, keyValue, '-1');
}
</script>
您可以像这样设置 Cookie
setCookie('test','1','1'); //(key,value,expiry in days)
你可以像这样获得饼干
getCookie('test');
最后,您可以像这样擦除 cookie
eraseCookie('test');
希望它将对某人有所帮助:)
编辑:
如果要将 cookie 设置为所有路径 / 页面 / 目录,则将 path 属性设置为 cookie
function setCookie(key, value, expiry) {
var expires = new Date();
expires.setTime(expires.getTime() + (expiry * 24 * 60 * 60 * 1000));
document.cookie = key + '=' + value + ';path=/' + ';expires=' + expires.toUTCString();
}
谢谢,vicky
您可以使用此处提供的插件。
https://plugins.jquery.com/cookie/
然后写一个 cookie 做$.cookie("test", 1);
要访问设置的 cookie,请执行$.cookie("test");
这是我使用的全局模块 -
var Cookie = {
Create: function (name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
document.cookie = name + "=" + value + expires + "; path=/";
},
Read: function (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;
},
Erase: function (name) {
Cookie.create(name, "", -1);
}
};
确保不要执行以下操作:
var a = $.cookie("cart").split(",");
然后,如果 cookie 不存在,调试器将返回一些无用的消息,例如 “.cookie 不是函数”。
始终先声明,然后在检查 null 后再进行拆分。像这样:
var a = $.cookie("cart");
if (a != null) {
var aa = a.split(",");
在浏览器中设置 Cookie 的简单示例:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>jquery.cookie Test Suite</title>
<script src="jquery-1.9.0.min.js"></script>
<script src="jquery.cookie.js"></script>
<script src="JSON-js-master/json.js"></script>
<script src="JSON-js-master/json_parse.js"></script>
<script>
$(function() {
if ($.cookie('cookieStore')) {
var data=JSON.parse($.cookie("cookieStore"));
$('#name').text(data[0]);
$('#address').text(data[1]);
}
$('#submit').on('click', function(){
var storeData = new Array();
storeData[0] = $('#inputName').val();
storeData[1] = $('#inputAddress').val();
$.cookie("cookieStore", JSON.stringify(storeData));
var data=JSON.parse($.cookie("cookieStore"));
$('#name').text(data[0]);
$('#address').text(data[1]);
});
});
</script>
</head>
<body>
<label for="inputName">Name</label>
<br />
<input type="text" id="inputName">
<br />
<br />
<label for="inputAddress">Address</label>
<br />
<input type="text" id="inputAddress">
<br />
<br />
<input type="submit" id="submit" value="Submit" />
<hr>
<p id="name"></p>
<br />
<p id="address"></p>
<br />
<hr>
</body>
</html>
简单只需复制 / 粘贴并使用此代码来设置您的 cookie。
这是使用 JavaScript 设置 Cookie 的方法:
下面的代码摘自https://www.w3schools.com/js/js_cookies.asp
function setCookie(cname, cvalue, exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays*24*60*60*1000)); var expires = "expires="+ d.toUTCString(); document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; }
现在,您可以使用以下功能获取 Cookie:
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 的方式:
function checkCookie() { var username = getCookie("username"); if (username != "") { alert("Welcome again " + username); } else { username = prompt("Please enter your name:", ""); if (username != "" && username != null) { setCookie("username", username, 365); } } }
如果要删除 cookie,只需将 expires 参数设置为经过的日期:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
您可以在此处使用 Mozilla 网站上的库
您将可以设置和获取这样的 Cookie
docCookies.setItem(name, value);
docCookies.getItem(name);
我认为 Fresher 给了我们很好的方法,但是有一个错误:
<script type="text/javascript">
function setCookie(key, value) {
var expires = new Date();
expires.setTime(expires.getTime() + (value * 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>
您应该在 getTime()附近添加 “值”;否则 cookie 将立即过期:)