Possible Duplicate:
How to enable cookies
The readCookie
is right under the greetUser
function. I put in the writeCookie
function but it causes the alert
boxes not to show. So I commented it out.
This is about the cookies not working. I'm suppose to sort the username it a variable so that iRock
will remember the name and use it in the prompt.
It seems like the last part of the code works because I get the alert
boxes, but I don't get the first and second alert boxes. The page is suppose to open in an alert box saying, "Hello, I am a pet rock." but it doesn't.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org /TR/xhtml1 /DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title&g开发者_如何学运维t;iRock - The Virtual Pet Rock</title>
<link href="donut_stylesheet/donut.css" rel="stylesheet" type="text/css" />
<script type ="text/javascript">
var userName;
function resizeRock(){
document.getElementById("rockImg").style.height = (document.body.clientHeight - 100) * 0.9;
}
function greetUser(){
userName = readCookie("rock_username");
if(userName)
alert("Hello " + userName + ", I missed you.");
else
alert("Hello, I am your pet rock");
}
function touchRock(){
if(userName)
alert("I like attention," + userName + ". Thank you.");
}
userName = prompt("What is your name?", "Enter name here.");
if(userName)
alert("It is good to meet you, " + userName + ".");
//writeCookie(irock_username", userName, 1 * 365);
document.getElementById("rockImg").src = "rock_happy.png";
setTimeout("document.getElementById(('rockImg').src = 'images/rock.png';", 5 * 60 * 1000);
</script>
</head>
<body onload="resizeRock(); greetUser(); onResize="resizeRock();">
<img id="rockImg" src="images/rock.png" alt="iRock" style="cursor:pointer" onClick="touchRock();" />
</body>
</html>
There are no built in readCookie
or writeCookie
functions in JavaScript. You will have to supply your own, like this.
function writeCookie(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);
}
精彩评论