jquery设置cookie问题
我使用此插件在我的页面上设置 cookie: https://github.com/carhartl/jquery- cookie
并在我的文档准备功能中添加了以下内容:
$.cookie('checkCook', '2')
在我的文档准备功能之后,我正在做一些事情并将 cookie 设置为 null,
$(document).ready(function() {
//setting the cokie
if($.cookie('checkCook') == '2'){
alert($.cookie('checkCook'));
$.cookie('checkCook', null);
}
})
但是直到我在每次刷新时收到警报为“2”浏览器。这有什么问题吗?
I am setting a cookie on my page, using this plugin : https://github.com/carhartl/jquery-cookie
and out of my document ready function i added this :
$.cookie('checkCook', '2')
after my document ready function i am doing some stuff and setting the cookie to null,
$(document).ready(function() {
//setting the cokie
if($.cookie('checkCook') == '2'){
alert($.cookie('checkCook'));
$.cookie('checkCook', null);
}
})
But till i am getting the alert as '2', in every refresh of my browser. Anything wrong with this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我理解正确的话,你的设置是这样的:
你所期望的是你对
$.cookie('checkCook', null); 的调用将删除 cookie,但在每次刷新时在该页面中,通过调用
$.cookie('checkCook', '2');
将 cookie 重置为“2”。由于
$.cookie('checkCook', '2');
位于 doc.ready 函数之外,因此浏览器一点击它就会调用它(请记住,页面是自上而下加载的) ,并且 doc.ready 块会被延迟,直到 dom 被加载。这意味着$.cookie('checkCook', '2');
代码在 doc.ready 块之前执行。这就是为什么您总是收到指示值为“2”的警报的原因。每次页面刷新时以及调用警报
之前,都会设置 cookie。您可以做的是将 cookie 设置代码包装在一个函数中,并从 doc.ready 调用它。这将延迟 cookie 的设置,直到执行警报代码之后。
If I understand correctly, you have something set up like this:
What you are expecting is that your call to
$.cookie('checkCook', null);
will delete the cookie, but on every refresh of the page, the cookie is reset to '2' with your call to$.cookie('checkCook', '2');
.Since
$.cookie('checkCook', '2');
is outside of your doc.ready function, it gets called as soon as the browser hits it (remember, the page is loaded top down), and the doc.ready block is delayed until the dom is loaded. This means that the$.cookie('checkCook', '2');
code is executed before the doc.ready block. That's why you are always getting the alert that states the value is '2'. The cookie is getting set on every page refresh, and before youralert
is called.What you could do is wrap the cookie setting code in a function and call that from doc.ready. This will delay the setting of the cookie until after the alert code is executed.
通过将过期时间设置为过去来清除 Cookie。
Cookies are cleared by setting expiration time to past.