2012-03-22 36 views
1

我有這個代碼來設置和檢查一個cookie,並在重定向之前(如果用戶點擊取消按鈕)我需要取消設置或刪除cookie。如何刪除Cookie之前重定向到JavaScript中的其他頁面?

function getCookie(c_name) { 
    if (document.cookie.length > 0) { 
     c_start = document.cookie.indexOf(c_name + "=") 
     if (c_start != -1) { 
      c_start = c_start + c_name.length + 1 
      c_end = document.cookie.indexOf(";", c_start) 
      if (c_end == -1) c_end = document.cookie.length 
      return unescape(document.cookie.substring(c_start, c_end)) 
     } 
    } 
    return ""; 
} 

function setCookie(c_name, value, expiredays) { 
    var exdate = new Date() 
    exdate.setDate(exdate.getDate() + expiredays) 
    document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : "; expires=" + exdate.toGMTString()) 
} 

function checkCookie() { 
    var todaysdate = new Date() 
    var day = todaysdate.getDay() 

    switch (day) { 
    case 1: 
     day = "Monday" 
     break 
    case 2: 
     day = "Tuesday" 
     break 
    case 3: 
     day = "Wednesday" 
     break 
    case 4: 
     day = "Thursday" 
     break 
    case 5: 
     day = "Friday" 
     break 
    case 6: 
     day = "Saturday" 
     break 
    case 0: 
     day = "Sunday" 
     break 
    } 

    var thedate = getCookie('thedate') 

    if (thedate != null && thedate != "") { 
     if (day == thedate) {} else { 
      alert('') 
     } 
    } else { 
     thedate = day 

     if (thedate != null && thedate != "") { 
      setCookie('thedate', thedate, 365) 
      // alert('dsadasdasdasdasdasdasd') 
      var answer = confirm("Please click on OK to continue loading my page, or CANCEL to be directed to the Yahoo site.") 
      if (!answer) { 

       window.location = "http://www.yahoo.com/"; 
      } 

     } 
    } 
} 

如何取消cookie的設置c_name

我確定這件事很容易,但是我無法取消設置這個cookie。

回答

1

只需設置一個空的cookie,並設置它在今天之前到期(即-1):

if (!answer) { 
    setCookie('thedate', '', -1); //using your already existing setCookie function 
    window.location="http://www.yahoo.com/"; 
} 

More details on cookies here

+0

謝謝,它的工作。 :) – Derfder 2012-03-22 11:58:30

0
function loaded() 
{ 
    document.cookie = "v0=1;"; 
    document.cookie = "v1=2;"; 

    alert(document.cookie); 
} 

function deletecook() 
{ 
    var d = new Date(); 
    document.cookie = "v0=1;expires=" + d.toGMTString() + ";" + ";"; 

    alert(document.cookie); 
} 
相關問題