2016-01-22 85 views
0

我使用jquery.cookie在用戶註冊簡報的模式中設置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

首先,可以只複製的問題,但你必須在按鍵ID的空間,這也有可能是默認的引導點擊事件導致你的事件沒有被調用:

//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可能是si mplified。你可以這樣試試:

$(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'); 
    }); 
}); 
+0

好吧,我明白你做了什麼!如果''.cookie('my_cookie',true,{'不是'$ .cookie('regNewsletter',true,{'??或者也許'my_cookie'沒有逗號 – Meules

+0

對不起,我更正了代碼現在應該是更好的可讀性 – yunicz

相關問題