设置两个不同值的cookie

时间:2016-01-22 15:09:09

标签: javascript jquery cookies

我正在使用jquery.cookie在用户注册简报的模式中设置一个cookie。

我有两个Cookie场景 1)模态显示,用户可以勾选“不再显示”复选框。 Cookie需要设置为7天。或者用户点击普通的“关闭/ X”按钮

2)用户填写表格并完成注册过程。单击“完成”按钮时,cookie需要设置为365天。

我不想在表单提交上设置cookie,因为人们仍然可以放弃表单。

我设法让复选框cookie工作但不是按钮cookie。两者都需要首先检查cookie是否存在,如果没有设置cookie取决于采取的行动。

我做错了什么?

所以我拥有的是:

//The checkbox
<div class='modal-footer'>
 <div class="checkbox pull-right">
   <label for="modal-checkbox">dont show again</label>
   <input class='modal-check' id="modal-checkbox" name='modal-check' type="checkbox">
 </div>
</div>

//The button
<div class='modal-footer'>
 <button type="submit" id="success--btn "class="btn btn-custom-2 btn-block" data-dismiss="modal" aria-label="Close">Finished!</button>          
</div>

脚本

 $(document).ready(function(){

    var my_cookie = $.cookie($('.modal-check').attr('name'));
    if (my_cookie && my_cookie == "true") {
      $(this).prop('checked', my_cookie);
    }
    else{
      setTimeout(function(){
        $('#newsletter').modal('show');
      }, secs);
    }
    $(".modal-check").change(function() {
      $.cookie($(this).attr("name"), $(this).prop('checked'), {
        path: '/',
        expires: 7
      });
    });
    $("#succes--btn").on("click", function () {
      $.cookie('my_cookie', '1234', {
        path: '/',
        expires: 365
      });
    }); 

1 个答案:

答案 0 :(得分:1)

首先,它可能只是复制问题,但你在按钮ID中有一个空格,而且默认的bootstrap click事件也可能导致你的事件没有被调用:

//The button
<div class='modal-footer'>
    <button type="submit" id="success--btn" class="btn btn-custom-2 btn-block" aria-label="Close">Finished!</button>          
</div>

JavaScript可以简化。你可以这样试试:

$(document).ready(function(){
    //keep it simple, I suppose the cookie name will not change after all
    var regNewsletterCookie = $.cookie('regNewsletter');
    if (!regNewsletterCookie) {
        //my_cookie undefined or my_cookie false ends here
        setTimeout(function(){
            $('#newsletter').modal('show');
        }, secs);
    }

    $(".modal-check").change(function() {
        $.cookie('regNewsletter', $(this).prop('checked'), {
        path: '/',
        expires: 7
    });
    //And there is also a typo in you selector succesS--btn
    $("#success--btn").on("click", function () {
        $.cookie('regNewsletter', true, {
            path: '/',
            expires: 365
        });
        $('#YourModalId').modal('hide');
    });
});
相关问题