2015-10-07 95 views
0

我已經使用了從git獲得的這段代碼。它的基本設置是設置一個cookie,以僅在首次訪問該網站時顯示一個彈出窗口。但是,我希望它只能設置24小時。所以如果有人在一兩天後回到網站,它會再次顯示。將Cookie設置爲一天後過期

(function ($) { 

    'use strict'; 

    $.fn.firstVisitPopup = function (settings) { 

     var $body = $('body'); 
     var $dialog = $(this); 
     var $blackout; 
     var setCookie = function (name, value) { 
      var date = new Date(), 
       expires = 'expires='; 
      date.setTime(date.getTime() + 31536000000); 
      expires += date.toGMTString(); 
      document.cookie = name + '=' + value + '; ' + expires + '; path=/'; 
     } 
     var getCookie = function (name) { 
      var allCookies = document.cookie.split(';'), 
       cookieCounter = 0, 
       currentCookie = ''; 
      for (cookieCounter = 0; cookieCounter < allCookies.length; cookieCounter++) { 
       currentCookie = allCookies[cookieCounter]; 
       while (currentCookie.charAt(0) === ' ') { 
        currentCookie = currentCookie.substring(1, currentCookie.length); 
       } 
       if (currentCookie.indexOf(name + '=') === 0) { 
        return currentCookie.substring(name.length + 1, currentCookie.length); 
       } 
      } 
      return false; 
     } 
     var showMessage = function() { 
      $blackout.show(); 
      $dialog.show(); 
     } 
     var hideMessage = function() { 
      $blackout.hide(); 
      $dialog.hide(); 
      setCookie('fvpp' + settings.cookieName, 'true'); 
     } 

     $body.append('<div id="fvpp-blackout"></div>'); 
     $dialog.append('<a id="fvpp-close">&#10006;</a>'); 
     $blackout = $('#fvpp-blackout'); 

     if (getCookie('fvpp' + settings.cookieName)) { 
      hideMessage(); 
     } else { 
      showMessage(); 
     } 

     $(settings.showAgainSelector).on('click', showMessage); 
     $body.on('click', '#fvpp-blackout, #fvpp-close', hideMessage); 

    }; 

})(jQuery); 
+0

因此將setTime更改爲一天 – epascarello

+0

31536000000是以ms爲單位的年份,因此將其更改爲以毫秒爲單位的1天 – Molda

回答

5

變化:

date.setTime(date.getTime() + 31536000000); 

到:

date.setDate(date.getDate() + 1); 

這增加了1天的日期。舊代碼添加365天。