2015-04-03 72 views
0

我有一個腳本,在單擊鏈接後設置cookie,然後當您再次訪問該頁面時,它將檢查cookie並提醒您已經在這裏。但是,我的代碼似乎不工作。任何1可以幫助嗎?使用javascript設置和檢查cookie

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
 
"http://www.w3.org/TR/html4/loose.dtd"> 
 

 
<html> 
 

 
<head> 
 
    <title></title> 
 
    <script type="text/javascript"> 
 
     function get_cookie("visited"){ 
 
      if (document.cookie.indexOf("visited") >= 0) { 
 
       // They've been here before. 
 
       alert("hello again"); 
 
      } 
 
    </script> 
 

 
</head> 
 

 
<body onload="get_cookie()"> 
 

 
    <script type="text/javascript"> 
 
     /* This function sets the cookie */ 
 
     function iLoveCookies() { 
 
       days = 30; // number of days to keep the cookie 
 
       myDate = new Date(); 
 
       myDate.setTime(myDate.getTime() + (days * 24 * 60 * 60 * 1000)); 
 
       document.cookie = 'cookieName=visited; expires=' + myDate.toGMTString(); 
 
      } 
 
      /* end of cookie function */ 
 

 

 
     
 
    </script> 
 

 
    <a href="#" onclick="iLoveCookies()">Set Cookie</a> 
 
</body> 
 
</html>

+0

你缺少您的getCookie功能關閉}。 – 2015-04-03 18:19:07

+1

'function get_cookie(「visited」){}'無效。 – Dhiraj 2015-04-03 18:19:54

+0

我拿出了}但問題仍然存在。我如何檢查我在這種情況下設置的Cookie。導致cookie正在設置,但沒有正確檢查 – Heli 2015-04-03 18:23:40

回答

2

它看起來像你基本上有拼寫錯誤造成的錯誤。您可能需要使用linter來檢查您的JavaScript,或至少查看您的瀏覽器的developer console,看看它告訴你什麼。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
 
"http://www.w3.org/TR/html4/loose.dtd"> 
 

 
<html> 
 

 
<head> 
 
    <title></title> 
 
    <script type="text/javascript"> 
 
     function get_cookie(){ 
 
      if (document.cookie.indexOf("visited") >= 0) { 
 
       // They've been here before. 
 
       alert("hello again"); 
 
      } 
 
      } 
 
    </script> 
 
    
 

 
</head> 
 

 
<body onload="get_cookie()"> 
 

 
    <script type="text/javascript"> 
 
     /* This function sets the cookie */ 
 
     function iLoveCookies() { 
 
       days = 30; // number of days to keep the cookie 
 
       myDate = new Date(); 
 
       myDate.setTime(myDate.getTime() + (days * 24 * 60 * 60 * 1000)); 
 
       document.cookie = 'cookieName=visited; expires=' + myDate.toGMTString(); 
 
      } 
 
      /* end of cookie function */ 
 
    </script> 
 

 
    <a href="#" onclick="iLoveCookies()">Set Cookie</a> 
 
    <a href="#" onclick="get_cookie()">Get Cookie</a> 
 
</body> 
 
</html>

+0

它現在的工作,謝謝 – Heli 2015-04-03 18:36:57

+0

很高興聽到它。僅供參考:您可以使用許多[現有庫/框架](https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie)。 – 2015-04-03 18:52:39