我正在尝试根据用户输入创建,检查并获取cookie,但是当我输入我的名字时,它不会保存cookie,反过来我不知道我的检查或获取功能是否正常工作。任何想法?
这是我的代码:
//capture the values and write to a cookie
function setCookie(Name, Value, Expiration) {
//set the expiry date
var expDate = new Date();
//check if the expiration parameter is not null
if (Expiration !== null) {
expDate.setDate(expDate.getDate() + Expiration);
//write the data to store
var cookieVal = escape(Value) + "; expires=" + expDate.toGMTString() + ";";
//store the cookie
document.cookie = Name + "=" + cookieVal;
} else {
alert("expiration is invalid");
}
}
function getCookie(Name) {
//capture all cookies and split into individual ones
var cookies=document.cookie.split(";");
//process each one
for(var i=0; i<cookies.length; i++){
//obtain the name of the cookie
var CName = cookies[i].substr(0,cookies[i].indexOf("="));
//obtain the value of the cookie
var CValue = cookies[i].substr(cookies[i].indexOf("=") + 1);
//replace any escaped characters
CName = CName.replace(/^\s+|\s+$/g, "");
//if the name of the cookie matches the name that was passed by the caller, return the associated cookie
if(Name == CName) {
return unescape(CValue);
}
}
//return a null value if the cookie isnt found
return null;
}
function checkName() {
//obtain the users name
var UserName = getCookie("Username");
//check for a user name
if((UserName == null) || (UserName == "")) {
//obtain a username from the user
UserName = prompt("please type your name");
//set a cookie for the username
setCookie("UserName", UserName, 365);
} else {
UserName = "welcome back " + UserName;
}
//display the users name on screen
var SetName = document.getElementById("name");
SetName.innerHTML = "hello " + UserName;
}
答案 0 :(得分:0)
@RGraham给出了下面的答案,现在似乎有效。
简单拼写错误:setCookie(&#34; UserName&#34;,UserName,365);但你是 检查用户名... var UserName = getCookie(&#34;用户名&#34;);
感谢。