我想练习创建cookie,我在互联网上找到了很多样本。我试图自己实现代码,但是当我测试它时,没有任何反应。这是代码:
<!DOCTYPE html>
<html>
<head>
<script>
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
function getCookie(cname) {
var name = cname + "=";
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);
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function cookieText() {
var username = document.getElementByID("sometext").value;
setCookie("username", user, 30);
}
function showCookie() {
var user=getCookie("username");
alert("Hello " + user);
}
</script>
</head>
<body>
<form>
<input type="text" id="someText"></input>
<input type="button" value="create cookie!" onClick="cookieText();"></input>
<input type="button" value="show the cookie!" onClick = "showCookie();"></input>
</form>
</body>
</html>
每当我按下show the cookie!
按钮(我已经在文本字段中输入了某些内容并且已经使create cookie!
按钮加入)时,没有任何反应。 JavaScript警报甚至没有显示。我想知道代码出错了。