javascript - 跨页面持久保存 jQuery Cookie

标签 javascript jquery cookies

我正在使用 jQuery Cookie 插件 ( https://github.com/carhartl/jquery-cookie ),但在我网站的不同页面上保留我的 cookie 时遇到了问题。

我有一段内容显示在每个页面上,一旦隐藏它就会像这样设置 cookie(为所有变量道歉,它们根本不相关:

// Binds the close event to the button.
$alert.on('click', function(e) {
    $alertWrap.fadeOut();

    // Sets the breaking-delete cookie to yes.
    $.cookie('breaking-bar-delete', 'yes', {expires: 7 });
});

当初始脚本触发时,它会检查 cookie 是否存在:

// If the current bar is not supressed and they are not in the editor, and they do not have a closed cookie it will setup the bar.
if ($.cookie('breaking-bar-delete') == undefined) {
  $alert.css("display","block");
}

// If there's no news, or they have the closed cookie for the current bar it hides it by default.
if ($.cookie('breaking-bar-delete') == 'yes') {
  $alert.parent().css("display","none");
}

现在这适用于您隐藏栏的路径,因此如果您刷新它不会重新显示。但是,如果您使用不同的路径访问网站的某个部分,它不会检测到 cookie 并显示内容。

当我最初提供 cookie 时,我是否可以设置某种配置,以便它在我网站的所有页面中持续存在?

最佳答案

Path :-

path

path: '/' Define the path where the cookie is valid.

By default the path of the cookie is the path of the page where the cookie was created (standard browser behavior).

If you want to make it available for instance across the entire domain use path: '/'.

Default: path of page where the cookie was created.

因此,对于您的 cookie:-

$.cookie('breaking-bar-delete', 'yes', { expires: 7, path: '/' });

关于javascript - 跨页面持久保存 jQuery Cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35434103/

相关文章:

jquery - 包含位置 : absolute elements inside of a div, 以便可以在其前后插入position:relative div

java - Tomcat 8 迁移 - 如何获取响应 cookie

javascript - window.open 在提交事件时请求浏览器的弹出权限

php - JQuery 和提交按钮

javascript - 我需要从浏览器中获取所有 cookie

ruby - 如何在 Ruby on Rails 中的一个 cookie 中存储多个值?

javascript - 将老式 javascript 实体转换为 ES6 类

javascript - 在复选框选择上提交 Django 表单

javascript - 内置 Javascript 函数的模拟结果

javascript - 使用 angularjs 从选项中获取整个对象