2015-09-23 32 views
0

我有以下jQuery代碼的問題。此代碼是更大的Yii項目的一部分。我希望這個顧問在我進入網站時可見,然後關閉它以保存cookie中的狀態。然後我重新加載頁面並關閉。我怎樣才能用這個代碼做到這一點?如何記住jQuery中cookie顧問的真/假狀態?

var adviserIsVisible = true, 
    adviserCookie = getCookie("adviser"), 

    if(adviserCookie != "") { 
     adviserIsVisible = adviserCookie; 
    } 

    if(adviserIsVisible == true){ 
     $("#adviser-slide-button").html("&lt");     
     $(".adviser-slide").animate({"left": "0px"}); 
     adviserIsVisible = false; 
    } 
    else { 
     $("#adviser-slide-button").html("&gt"); 
     $(".adviser-slide").animate({"left": "-206px"}); 
     adviserIsVisible = true; 
    } 

    $("#adviser-slide-button").live("click",function(){ 
     if(adviserIsVisible == true){ 
      $("#adviser-slide-button").html("&lt"); 
      $(".adviser-slide").animate({"left": "0px"}); 
      adviserIsVisible = false; 
     } 
     else{  
      $("#adviser-slide-button").html("&gt"); 
      $(".adviser-slide").animate({"left": "-206px"}); 
      adviserIsVisible = true; 
     } 

    setCookie("adviser", adviserIsVisible, 1); 


    }); 
+0

這將有助於解釋目前與您的代碼發生了什麼,以及您在哪裏有問題。 –

+0

你可以給我一個小提琴,顧問幻燈片嗎?所以我可以給你一個更好的例子在我的回答 –

+0

如果你檢查我的答案,我已經創建了一個例子,它向你展示瞭如何做滑塊。我在'.animate({});'中使用'margin-left'而不是'left'來工作 –

回答

0

的方式我去設置和檢索餅乾是我已經爲下創建了兩個功能:使用SetTheCookieGetTheCookie

function SetTheCookie(key, value) 
{ 
    // Expire date for cookie 
    var expires = new Date(); 
    // Set expire date for cookie 
    expires.setTime(expires.getTime() + (1 * 24 * 60 * 60 * 1000)); 
    // Set cookie key and value which is passed in by parameters 
    document.cookie = key + '=' + value + ';expires=' + expires.toUTCString(); 
} 

function GetTheCookie(key) 
{ 
    // Check to see if there is a cookie matching the value passed in by parameter 
    var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)'); 
    return keyValue ? keyValue[2] : null; 
} 

例子:

EXAMPLE JSFIDDLE