2011-08-18 61 views
0

我正在檢查,獲取並設置一個cookie來跟蹤上次訪問的頁面。爲了做到這一點,我打電話給javascript onload。問題是當我執行這個js時,它反覆引用。非常像一個即使在鼠標移動。但除了onload之外,我沒有任何其他事件。Javascript window.location被越來越多地調用IE-8

這裏是我的JS:

<script type='text/javascript'> 
    //<![CDATA[ 

    window.onload = function(event){   
     var currentPage = window.location.href; 
     var lastVisited = getCookie('udis'); 
     var sessionId= getCookie('udisSession'); 
     if(lastVisited === null || lastVisited === undefined){ 
      setCookie("udis", currentPage, 365); 
      lastVisited = getCookie('udis'); 
     } 
     if(sessionId === null || sessionId === undefined){ 
      setSessionCookie('udisSession'); 
      if(lastVisited !== currentPage){ 
       window.location.href = lastVisited;   
      }   
     } 
     setCookie("udis", currentPage, 365); 
     updateBreadCrumb(); 
    } 

     function getCookie(c_name) { 
      var i,x,y,ARRcookies=document.cookie.split(";"); 
      for (i=0;i<ARRcookies.length;i++){ 
       x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("=")); 
       y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1); 
       x=x.replace(/^\s+|\s+$/g,""); 
       if (x==c_name) { 
        return unescape(y); 
       } 
      } 
     } 
     function setSessionCookie(c_name){ 
     document.cookie=c_name + "=" + 'testSession'+'; expires=; path=/'; 
    } 

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


    //]]> 
    </script> 

上面的代碼完美的作品在Firefox,但在IE-8這是造成該頁面一次又一次的調用。

回答

3

設置cookie時,分號後需要一個空格。您還需要過期日期。如果您希望製作一個在瀏覽器關閉時過期的cookie,請刪除過期日期子句。

function setSessionCookie(c_name){ 
    document.cookie=c_name + "=" + 'testSession'+'; path=/'; 
} 

我建議你使用的功能從here

function createCookie(name,value,days) { 
    if (days) { 
     var date = new Date(); 
     date.setTime(date.getTime()+(days*24*60*60*1000)); 
     var expires = "; expires="+date.toGMTString(); 
    } 
    else var expires = ""; 
    document.cookie = name+"="+value+expires+"; path=/"; 
} 

function readCookie(name) { 
    var nameEQ = name + "="; 
    var ca = document.cookie.split(';'); 
    for(var i=0;i < ca.length;i++) { 
     var c = ca[i]; 
     while (c.charAt(0)==' ') c = c.substring(1,c.length); 
     if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); 
    } 
    return null; 
} 

function eraseCookie(name) { 
    createCookie(name,"",-1); 
} 

而不是使用setSessionCookie(c_name)的,你可以使用createCookie(c_name, 'testSession');

+0

真!我試過了。但看起來不是原因。 – Rachel

+0

不錯,我不知道! –

+0

@Rachel:你沒有給它一個過期日期,所以它馬上過期了。 –