2016-05-23 65 views
1

我正在嘗試創建基於JS Cookie的新聞快訊部分。我有一切正常工作,但顯示內容是否存在或不存在的cookie。我正在使用JS-Cookie腳本。顯示基於Javascript Cookie的內容

我希望本節僅在用戶沒有設置cookie時才顯示。基本上,如果這是他們第一次查看網站或在cookie過期後(30天)。

現在,即使我使用私人瀏覽器,不同的電腦等,它一直說cookie已設置並顯示內容。我當前的代碼在沒有設置時會顯示它,所以除非您刪除!來自if語句。

我正在使用js-cookie作爲cookie。你可以看到codepen http://codepen.io/byoungz/pen/YqoxJy

var emailSignup = document.getElementById("tgs-subscribe-bar"), 
    screenWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0); 

$('#tgs-subscribe-bar').hide(); 


if (Cookies.get('emailsignup') == 'null') { 
    if (screenWidth < 768) { 
    //code for smaller screens  
    setTimeout(function() { 
      $('#tgs-subscribe-bar').slideDown(); 
    }, 4000); 

    } else { 
     //code for larger 
     setTimeout(function() { 
       $('#tgs-subscribe-bar').slideDown(); 
     }, 1000); 
    } 

    Cookies.set('emailsignup', 'seenemail', { expires: 30, path: '/' }); 
} 

$('.email-exit').click(function() {  
     $("#tgs-subscribe-bar").slideToggle(); 
}); 
+1

你不設置cookie在檢查它的存在之前? 'Cookies.set('emailsignup','seenemail',{expires:30,path:'/'});' – Cornwell

+1

是的,我注意到這個錯誤和更新的代碼。很快會發布編輯更新。 –

回答

1

如果cookie不存在,它會返回undefined不是

試試這個:

var emailSignup = document.getElementById("tgs-subscribe-bar"), 
    screenWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0); 

$('#tgs-subscribe-bar').hide(); 


if (!Cookies.get('emailsignup')) { 
    if (screenWidth < 768) { 
    //code for smaller screens  
    setTimeout(function() { 
      $('#tgs-subscribe-bar').slideDown(); 
    }, 4000); 

    } else { 
     //code for larger 
     setTimeout(function() { 
       $('#tgs-subscribe-bar').slideDown(); 
     }, 1000); 
    } 

    Cookies.set('emailsignup', 'seenemail', { expires: 30, path: '/' }); 
} 

$('.email-exit').click(function() {  
     $("#tgs-subscribe-bar").slideToggle(); 
}); 
+2

謝謝!這很有效,我看到了我的錯誤。 –

+1

@ 4everYoungz太棒了,你知道問題的地方,而不是隻複製代碼:) – Cornwell