2017-02-09 44 views
0

我正在學習JavaScript,並且我發現這個問題已被多次詢問,但我無法得到它爲我工作。 我想要做的是每天顯示一次bootstrap模式。在頁面上設置Cookie以顯示每天一次的引導彈出窗口

我至今是:

function setCookie(cookiename, cookievalue, expdays) { 
    var d = new Date(); 
    d.setTime(d.getTime()+(expdays * 24 * 60 * 60 * 1000)); 
    var expires = "expires=" + d.toGMTString(); 
    document.cookie = cookiename + "=" + cookievalue + "; " + expires; 
} 

function getCookie(cookiename) { 
    var name = cookiename + "="; 
    var ca = document.cookie.split(';'); 
    for(var i = 0; i < ca.length; i++) { 
    var c = ca[i].trim(); 
    if (c.indexOf(name) == 0) return c.substring(name.length, c.length); 
} 


//I want to check if there is a cookie. 
//if I have not set a cookie, I want to show my modal, 
//if there is a cookie then return; 
//The cookie should expire in one day. 
function checkCookie() { 
    var showed = getCookie("showed"); 
    if (showed != null && showed != "") { 
     var date = new Date(showed).getDate(); 
     var currentDate = new Date().getDate(); 

     if (currentDate > date) { 
      return true; 
     } 
     return false; 
    } 
    return true; 
} 

現在,如果我改變的最後一個真正的回報;返回假;我的模態不顯示。 現在,我每次都看到模態。 我在做什麼錯? 我該如何解決這個問題?

+0

你可以發佈您設置cookie的方式嗎? – misterwolf

+0

我在我的函數setCookie – NewDev

+0

中設置cookie是的,但是指令是什麼? ,因爲我測試了你的代碼,並且一切看起來都很好。我不認爲你有日期問題! – misterwolf

回答

0

function setCookie(cookiename, cookievalue, expdays) { 
 
    var d = new Date(); 
 
    d.setTime(d.getTime()+(expdays * 24 * 60 * 60 * 1000)); 
 
    var expires = "expires=" + d.toGMTString(); 
 
    document.cookie = cookiename + "=" + cookievalue + "; " + expires; 
 
} 
 

 
    function getCookie(cookiename) { 
 
    var name = cookiename + "="; 
 
    var startPos = document.cookie.indexOf(name); 
 
    if(startPos == -1) return null; 
 
    startPos+=(name.length); 
 
    if(document.cookie.indexOf(";",startPos) == -1){ 
 
    return document.cookie.substring(startPos,document.cookie.length); 
 
    } 
 
    else{ 
 
    return document.cookie.substring(startPos,document.cookie.indexOf(';',startPos)); 
 
    } 
 
return null; 
 
} 
 

 

 
//I want to check if there is a cookie. 
 
//if I have not set a cookie, I want to show my modal, 
 
//if there is a cookie then return; 
 
//The cookie should expire in one day. 
 
function checkCookie() { 
 
    var showed = getCookie("showed"); 
 
    if (showed != null && showed != "") { 
 
     var date = new Date(showed).getDate(); 
 
     var currentDate = new Date().getDate(); 
 

 
     if (currentDate > date) { 
 
      return true; 
 
     } 
 
     return false; 
 
    } 
 
    return true; 
 
}

還設置cookie時, 使用

setCookie('showed',new Date().toGMTString(),1); 

因爲我們使用的cookie的值,而不是過期的cookie的時間來檢查。所以價值必須是日期字符串

+0

編輯getCookie。現在檢查它 –

+0

我不認爲有獲取或設置cookie的問題。我只需要能夠檢查是否有cookie。 – NewDev

相關問題