我正在尝试创建一个脚本,当用户打开网站时,他或她会受到提示的欢迎,并且在提醒之后会说欢迎,但是在提示中输入的内容将设置1分钟的cookie我面临的问题是:
1.警报未显示
2. Cookie不会设置
function checkCookie()
{
var username=getCookie("username");
if (username!=null && username!="") {
alert("Welcome again "+ username);
}
else {
username=prompt("Please input name:","");
if (username !=null && username!="") {
setCookie("username", username, 365);
}
else {
alert("Error");
}
}
}
function setCookie (cname,cvalue,exdays)
{
var d = new Date();
d.setTime (d.getTime()+ (10*1000));
var expires ="; expires= "+ d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires; +"; path /";
}
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 "";
}
答案 0 :(得分:0)
尝试将var expires ="; expires= "+ d.toGMTString();
替换为var expires ="; expires= "+ d.toUTCString();
过期时间保存为Unix时间戳。
修改强> 您还需要执行checkCookie函数。我觉得这很明显。
答案 1 :(得分:0)
这是你的代码的jsfiddle: https://jsfiddle.net/19yp8ucd/3/。 它工作正常。你只需要调用checkCookie()函数。
checkCookie();
查看小提琴的.js中的最后一行。
此外,您没有使用setCookie()函数中的天数。您可以在此处检查setCookie(),getCookie(),eraseCookie()的良好实现:https://stackoverflow.com/a/24103596/3946520