【发布时间】:2021-02-11 16:37:59
【问题描述】:
我正在尝试在网页上实现 cookie。我无法让它正常运行。我也想存储一些变量的值。我意识到这非常广泛,但我对 JavaScript cookie 知之甚少,我正在研究 w3schools 示例。这是我目前所拥有的:
var days=365;
function setCookie(child,user,days) {
var exdate=new Date();
exdate.setDate(exdate.getDate() + days);
var child=escape(user) + ((365==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=child + "=" + child;
}
function getCookie(child) {
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++) {
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==child) {
return unescape(y);
}
}
}
function checkCookie() {
var username=getCookie("username");
if (username!=null && username!="") {
alert("Welcome again " + username);
} else {
username=prompt("Please enter your name:","");
if (username!=null && username!="") {
setCookie("username",username,days);
}
}
}
【问题讨论】:
-
功能需求是什么? “我正在尝试实施 cookie”确实没有任何东西可以引导您朝着正确的方向前进。
-
您的参数之一是“365”。这不是合法的 JavaScript 标识符,可能会导致一些问题。
-
@BalusC:我希望它通过让他们在提示框中输入他们的姓名来跟踪访问该页面的用户,然后将他们的“分数”存储在一个递增变量中(我我猜我只需要在 cookie 中添加一个“var”来保存包含用户“分数”的“var”。...如果这有任何意义
-
@zzzBov:感谢您的链接。解决问题
标签: javascript cookies