如何使用jQuery删除Cookie? [英] How to delete a cookie using jQuery?

查看:102
本文介绍了如何使用jQuery删除Cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用jQuery删除cookie;我已经尝试过了:

I want to use jQuery to delete cookies; I have tried this:

$.cookie('name', '', { expires: -1 });

但是当我刷新页面时,cookie仍然存在:

But when I refresh the page, the cookie is still there:

alert('name:' +$.cookie('name'));

为什么?

推荐答案

要使用JQuery删除cookie,请将值设置为null:

To delete a cookie with JQuery, set the value to null:

$.cookie("name", null, { path: '/' });

最终的解决方案是在访问cookie时显式指定path属性,因为OP从不同目录中的多个页面访问cookie,因此默认路径是不同的(原始问题未对此进行描述).在下面的讨论中发现了该解决方案,该解决方案解释了为什么接受此答案-尽管不正确.

The final solution was to explicitly specify the path property whenever accessing the cookie, because the OP accesses the cookie from multiple pages in different directories, and thus the default paths were different (this was not described in the original question). The solution was discovered in discussion below, which explains why this answer was accepted - despite not being correct.

对于某些版本的jQ cookie,上述解决方案会将cookie设置为字符串null.因此不删除cookie.改用下面建议的代码.

For some versions jQ cookie the solution above will set the cookie to string null. Thus not removing the cookie. Use the code as suggested below instead.

$.removeCookie('the_cookie', { path: '/' });

这篇关于如何使用jQuery删除Cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆