jquery - 设置和更新全局 jQuery cookie
问题描述
我正在构建一个基于选择设置大量 cookie 的站点。cookie 会更新并保存,但是当我导航到另一个页面时,选择不会全局存储。我试过使用 path: / 它只记住我访问该页面时的选择。
我正在存储一个 cookie,它在选定选项的面板中呈现一个列表,它也存储在一个隐藏字段中。
我在下面有一些代码,路径在正确的位置吗?
jQuery(document).ready(function () {
jQuery("ul.activities_list").append(jQuery.cookie("listItem"), {
expires: 7,
path: '/'
}); //<---end of $.cookie);
jQuery(".activity").on("click", ".add_activity", function() {
// jQuery(".add_activity").live('click',function () {
var title = jQuery(this).parent().parent().find('.title').html();
// Add activity item to the panel list.
jQuery("ul.activities_list").prepend(jQuery('<li>'+title+'<button id="remove_item" class="button is-primary is-white">Remove</button></li>'));
jQuery.cookie("listItem", ((jQuery.cookie("listItem") ? jQuery.cookie("listItem") : '') + jQuery('<li>'+title+'<button id="remove_item" class="button is-primary is-white">Remove</button></li></li>').clone().wrap('<div />').parent().html(), '/'));
jQuery.cookie("listItemTitle", ((jQuery.cookie("listItemTitle") ? jQuery.cookie("listItemTitle") : ', ') + title));
console.log(jQuery.cookie("listItem")) });
jQuery("#remove_item").live('click',function () {
jQuery(this).parent().remove();
var removed_item = jQuery('.activities_list').html();
jQuery.cookie("listItem", removed_item);
jQuery.cookie("listItemTitle", removed_item);
});
});```
解决方案
这应该有助于:
$.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 是在与当前路径不同的路径上创建的,您可能希望指定路径参数:
var cookieValue = $.cookie("test", { path: '/foo' });
如何使用 jQuery 设置/取消设置 cookie?
推荐阅读
- asp.net - 如何将 Azure 服务调用添加到 appsettings.json
- javascript - 创建或删除新用户后更新用户列表
- excel - 如何使用 VBA 从它的第一个行字段中获取实际的可透视数据
- fortran - 关于 MPI_SEND 和 MPI_RECV 命令的问题
- java - 无法插入到 mysql 中的枚举类型
- linux - net.DialTCP 在 Linux 上产生“连接被拒绝”错误,但在 Windows 上没有
- json - 如果我使用 JSON Schema 的 if-else 条件,是否有办法针对 JSON 中存在的任何附加键引发错误?
- google-cloud-platform - 有没有办法一次清除多个表?
- javascript - javascript API导入和导出问题
- javascript - Upsert 实现委托更新但不委托添加