如何使用jQuery设置和取消设置cookie,例如创建一个名为test的cookie并将值设置为1?
当前回答
不需要特别使用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);
}
看一看
我如何删除一个现有的类名,并添加一个新的与jQuery和cookies?
其他回答
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上的文档。
2019年4月前(老)
查看插件:
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");
更新(2015年4月):
正如下面的评论所述,开发原始插件的团队已经在一个新项目(https://github.com/js-cookie/js-cookie)中删除了jQuery依赖项,该项目具有与jQuery版本相同的功能和通用语法。显然,原来的插件并没有去任何地方。
在浏览器中设置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。
我认为Vignesh Pichamani的回答是最简单明了的。只是给他增加了设置过期天数的能力:
编辑:还增加了“永不过期”选项,如果没有设置天数
function setCookie(key, value, days) {
var expires = new Date();
if (days) {
expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000));
document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
} else {
document.cookie = key + '=' + value + ';expires=Fri, 30 Dec 9999 23:59:59 GMT;';
}
}
function getCookie(key) {
var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
return keyValue ? keyValue[2] : null;
}
设置cookie:
setCookie('myData', 1, 30); // myData=1 for 30 days.
setCookie('myData', 1); // myData=1 'forever' (until the year 9999)
与之前的答案相比,我减少了操作的数量,我使用以下方法。
function setCookie(name, value, expiry) {
let d = new Date();
d.setTime(d.getTime() + (expiry*86400000));
document.cookie = name + "=" + value + ";" + "expires=" + d.toUTCString() + ";path=/";
}
function getCookie(name) {
let cookie = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
return cookie ? cookie[2] : null;
}
function eatCookie(name) {
setCookie(name, "", -1);
}
确保不要做这样的事情:
var a = $.cookie("cart").split(",");
然后,如果cookie不存在,调试器将返回一些无用的消息,如“。Cookie不是一个函数”。
总是先声明,然后在检查null后进行拆分。是这样的:
var a = $.cookie("cart");
if (a != null) {
var aa = a.split(",");
推荐文章
- 在数组中获取所有选中的复选框
- 如何为Firebase构建云函数,以便从多个文件部署多个函数?
- 如何发送推送通知到web浏览器?
- AngularJS:工厂和服务?
- js:将一个组件包装成另一个组件
- 父ng-repeat从子ng-repeat的访问索引
- JSHint和jQuery: '$'没有定义
- 模仿JavaScript中的集合?
- 用JavaScript验证电话号码
- 如何在HTML5中改变视频的播放速度?
- 谷歌地图API v3:我可以setZoom后fitBounds?
- 用jQuery检查Internet连接是否存在?
- 如何使用滑动(或显示)函数在一个表行?
- ES6/2015中的null安全属性访问(和条件赋值)
- 与push()相反;