首页 > 解决方案 > 设置和更新全局 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);

    });
});```

标签: jquerycookies

解决方案


这应该有助于:

$.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?


推荐阅读