【问题标题】:set cookies with different expiration dates设置不同有效期的cookies
【发布时间】:2025-12-24 21:10:06
【问题描述】:

我对 javascript 很陌生,所以我希望有人可以帮助我解决这个问题。我在这里使用 javascipt cookie 文件:https://github.com/carhartl/jquery-cookie,并尝试根据是否勾选复选框来设置具有不同到期日期的不同 cookie。基本上,如果勾选该框,它会设置一个 7 天到期的 cookie,如果没有勾选,它会设置一个 1 天后到期的 cookie。这是我到目前为止所得到的,但它根本没有设置 cookie。

谢谢。

$(document).ready(function() {

//check if modal cookie is present

    if ($.cookie('modal_shown') == null) {

//check if checkbox is checked
//if so, set the cookie to expire after 7 days

        if ($('#checkbox1').prop('checked')) {
            $.cookie('modal_shown', 'yes', { expires: 7, path: '/' });
            }

//if not checked, set the cookie to expire after 1 day

        else {
            $.cookie('modal_shown', 'yes', { expires: 1, path: '/' });
            }
        $('#thisModal').reveal();
    }
});

【问题讨论】:

    标签: javascript jquery cookies jquery-cookie


    【解决方案1】:
    $.cookie('modal_shown', 'yes', { expires: ($('#checkbox1').prop('checked') ? 7 : 1), path: '/' });
    

    这是使用简写 if 语句来确定复选框是否被选中

    【讨论】:

    • 您好,感谢您的帮助,看起来它正确设置了 cookie,但我应该解释一下它做得更好的地方。第一部分检查是否有 cookie。 modal_shown ,存在。如果没有,它会导致出现一个模式窗口并设置 cookie。如果它存在,它什么也不做。我可以添加 $('#thisModal').reveal();在某处加入您的代码,以便在不存在 cookie 时出现模式窗口?
    • 因为 if 语句是简写的,所以之后简单地添加代码来显示模式会更容易
    最近更新 更多