【问题标题】:How do I use this jQuery plugin to delete a cookie?如何使用这个 jQuery 插件删除 cookie?
【发布时间】:2013-08-25 11:22:48
【问题描述】:

首先,为了显示 cookie,我使用了来自 electrictoolbox.com 的代码。

然后我做了一个表格来添加一些cookie:

<form class="cokies" method="post">
<input class="query" name="q" type="text" />
<input type="submit" name="save" value="saving">
<a>Delete Cookies</a>
</form>
$(document).ready(function(){
$('.cokies a').click(function(){
    $.cookie('q', null);
});

remember('[name=q]');

这个函数来自komodomedia.com

function remember( selector ){
    $(selector).each(function(){
        //if this item has been cookied, restore it
        var name = $(this).attr('name');
        if( $.cookie( name ) ){
            $(this).val( $.cookie(name) );
        }

        //assign a change function to the item to cookie it
        $(this).change(function(){
            $.cookie(name, $(this).val(), { path: '/', expires: 365 });
        });
    });
}

问题是,我不知道如何删除 cookie。

【问题讨论】:

    标签: jquery jquery-plugins cookies


    【解决方案1】:

    要删除 cookie,只需将 expires: 设置为负整数值。

    示例:

    $.cookie(name, $(this).val(), { path: '/', expires: -5 });

    【讨论】:

    • 如果它有效,请打勾,其他提出此问题的人都知道正确答案。
    【解决方案2】:

    Cookie 插件的新版本已经问世,并提供以下方便的语法:

    $.removeCookie('q');
    

    【讨论】:

    • 确保将路径设置为与最初设置 cookie 相同的路径:$.removeCookie('q', { path: '/' });
    【解决方案3】:

    jquery cookie 脚本有一个 bug .... 更改脚本 jquery.cookie.js 的开头可能会更好:

    jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
            options.path = "/";
    
        }
     ....
    

    在这种情况下,您将能够按预期删除 cookie。

    【讨论】:

      【解决方案4】:

      $.removeCookie("COOKIE_NAME",{domain:'.domain.com',path:'/'});

      检查 cookie 的路径和域,并确保将它们包含在 $.cookie 插件的额外参数中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-09
        • 1970-01-01
        • 2012-07-01
        • 2011-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多