0

我想制作一个 cokkie,它可以在用户在地图上选择区域时保存我在 netsoltech.com 上选择的区域,它可以保存 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>
4

1 回答 1

0

Try this

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

and the HTML

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

JSFiddle

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

于 2012-12-27T08:32:15.063 回答