我正在尝试编写一些 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/