我试图将cookie的值转换为全局变量,然后我可以使用document.getElementById
将其放入div中。
这是我的代码 - 它完全按照它记住cookie的事实运作,但它只是不会做一行,我已经清楚地概述了你的评论。
这是我的所有代码......
<!DOCTYPE HTML>
<html>
<head>
<script>
var globalVar = "";
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 checkCookie() {
var user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
globalVar = getCookie("username");
document.getElementById("demo").innerHTML = globalVar; /* THIS LINE DON'T WORK WHY NOT! THE ONE BELOW DOES IN THE CHANGE COOKIE FUNCTION DOES! */
} else {
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
function changeCookie() {
var user = getCookie("username");
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
document.getElementById("demo").innerHTML = user; /* THIS WORKS! */
}
checkCookie();
</script>
</head>
<body>
<div id="demo"></div>
<button onclick="changeCookie()">Change username</button>
</body>
</html>
答案 0 :(得分:1)
尝试在页面加载完成后立即调用checkCookie()
。
<body onload="checkCookie()">
另一种方法是将脚本标记移动到页面的末尾,就在body
的结束标记之前,如下所示:
<html>
<body>
<div id="demo"></div>
<button></button>
<!-- the rest of the page's HTML here -->
<script>
....
.... your script code here
....
....
checkCookie();
</scirpt>
</body>
</html>
答案 1 :(得分:-1)
您只是在案例陈述的第一部分中将html分配到"demo"
,您需要将其添加到第二部分,并分配user
变量,而不是globalVar
。也可以按照其他答案中的建议将代码放在正文的末尾。
function checkCookie() {
var user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
globalVar = getCookie("username");
document.getElementById("demo").innerHTML = globalVar;
} else {
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
setCookie("username", user, 30);
document.getElementById("demo").innerHTML = user;
}
}
}