我需要一个JavaScript代码段来记住用户选择(与cookie一起存储)。用户选择国家/地区和城市后,应将其重定向到特定页面,具体取决于之前的选择。
他们也可以随时改变国家和城市。
答案 0 :(得分:0)
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000)); //set d to x days (e.g. 30 days (= 2592000 seconds))
var expires = "expires="+d.toUTCString(); //set to valid date
document.cookie = cname + "=" + cvalue + "; " + expires; //set cookie
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';'); //put all the cookies in the document into an array, called 'ca'
for (var i=0; i<ca.length; i++) { //for each cookie
var c = ca[i]; //set 'c' to that cookie
while (c.charAt(0)==' ') c = c.substring(1); //get rid of superfluous characters
if (c.indexOf(name) == 0) //if 'c' == 'cname' (e.g. the cookie you're checking for
return c.substring(name.length,c.length); //return the value of that cookie
}
return "";
}
function onSelect(country, city) {
//call this function when the user has selected their country and city
setCookie("country", country, 30);
}
if (getCookie("country") && getCookie("city")) {
//this function will run automatically at first,
//if the user has already selected country and city (i.e. those cookies already exist)
//redirect to specific page
}