2012-12-27 86 views
0

我想做一個cokkie,它可以保存我選擇的區域在netsoltech.com上,只要用戶選擇地圖上的區域它可以保存cookie,當下一次用戶進入域時,自動轉到第一次點擊區域頁面我有這樣的代碼 但問題是,當用戶來到在未來的時間,然後第一個區域選擇頁面來話,就可以刷新,並轉到區域頁面..不是自動...記住cookie

<script> 
/* 
    Cookie script - Scott Andrew 
    Popup script, Copyright 2005, Sandeep Gangadharan 
*/ 

function newCookie(name,value,days) { 
var days = 10; // the number at the left reflects the number of days for the cookie to last 
       // modify it according to your needs 
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 nameSG = name + "="; 
    var nuller = ''; 
    if (document.cookie.indexOf(nameSG) == -1) 
    return nuller; 

    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(nameSG) == 0) return c.substring(nameSG.length,c.length); } 
    return null; } 

function eraseCookie(name) { 
    newCookie(name,"",1); } 

function toMem(region) { 

    newCookie('region', region);  
    window.location= "http://www.netsoltech.com/"+region+"/index"; 
} 


function remCookie() { 

window.location= "http://www.netsoltech.com/"+readCookie("region")+"/index"; 

} 

function addLoadEvent(func) { 
    var oldonload = window.onload; 
    if (typeof window.onload != 'function') { 
    window.onload = func; 
    } else { 
    window.onload = function() { 
     if (oldonload) { 
     oldonload(); 
     } 
     func(); 
    } 
    } 
} 

addLoadEvent(function() { 
    remCookie(); 
}); 


</script> 

回答

0

試試這個

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; 

    //redirect here 
} 

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 checkCookie() { 
    var region = getCookie("region"); 
    if (region != null && region != "") { 
     alert("redirect to " + region); //replace this with redirect 
    } 
} 

checkCookie(); //check this on page load 

HTML

<a href="#" onclick="setCookie('region', 'europe', 365); return false;">europe</a> 

的jsfiddle

http://jsfiddle.net/YtF2B/6/