javascript - 使用 jQuery 设置 cookie 时出现问题

标签 javascript jquery jquery-cookie

我正在尝试编写一些 jQuery,当页面加载时,它会检查是否已设置 cookie。如果尚未设置,则会打开一个模式,并将 cookie 设置为 6 小时。

似乎我的 cookie 没有被设置,并且无论 cookie 是否设置,我在 if/else 语句中都没有得到任何 console.log 语句。在控制台中,当我输入 $.cookie('email-signup') 时,我收到错误消息“无法读取未定义的属性 'cookie'。

我以前从未真正这样做过,所以任何帮助或建议将非常感激!

我的 jQuery 是:

jQuery(document).ready(function($) {
   if (!!$.cookie('email-signup')) {
        SetNewsletterCookie(email);
        console.log('loaded');

    }

   function SetNewsletterCookie(email) {
      $('#modalnewslettercontent').html('<iframe frameborder="0" marginwidth="0" marginheight="0" scrolling="no" width="100%" height="400" src="'+themePath+'views/newsletter-signup.html"></iframe>');

         var date = new Date();
         var minutes = 180;
         date.setTime(date.getTime() + (minutes * 60 * 1000));
         $.cookie('email-signup', 1, {expires: date, path: '/'});
         console.log('cookie set');

    }   
 });

最佳答案

根据Jquery-Cookie的docs ,您的 var 语句创建一个变量而不是 cookie。用他们的例子再试一次:

Create session cookie:

$.cookie('name', 'value');

Create expiring cookie, 7 days from then:

$.cookie('name', 'value', { expires: 7 });

Create expiring cookie, valid across entire site:

$.cookie('name', 'value', { expires: 7, path: '/' });

关于javascript - 使用 jQuery 设置 cookie 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41265853/

相关文章:

jquery - 无法在浏览器 cookie 中存储带有名称和值的数据

javascript - 我想从我的日期中删除秒和毫秒

javascript - 页面加载时连接中断 - Firefox - Firebase - signInWithPopup()

javascript - 如果找到,则使用不同的值更新嵌套属性,否则添加它

单击按钮时的 jquery 对话框

java - httpheader 中的编码问题导致 struts 2

jquery - 单击时的简单切换类不适用于表格

javascript - PHPMailer 返回 AJAX

JQuery 插件使用出现 "undefined"错误

javascript - 在 Javascript 开关语句上设置 Cookie