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

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

问题描述

我想用jQuery删除cookies;我试过这个:

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天全站免登陆