我的代码如下-
var userName_cookie = document.cookie.split("; ").find(row => row.startsWith("username")).split("=")[1];
function noUserName() {
console.log("noUserName()");
document.getElementById("known").style.display = "none"; // make sure that the known div is hidden
document.getElementById("not-known").style.display = "block";
document.getElementById("submit-btn").onclick = function() {
console.log("Submit btn clicked")
userName_cookie = document.getElementById("enter-name").value;
userNameKnown();
}
}
function userNameKnown() {
// add user name to cookie
userName_cookie = document.getElementById("enter-name").value;
document.getElementById("not-known").style.display = "none"; // make sure that the unknown div is hidden
document.getElementById("known").style.display = "block";
// edit known div to show username
document.getElementById("hello").innerText = `Hello, ${userName_cookie}`
// time (good morning, good evening etc.)
var date = new Date();
var hours = date.getHours();
if(hours < 12) {
document.getElementById("time").innerText = `Good Morning`;
} else if(hours == 12) {
document.getElementById("time").innerText = `Good Noon? or Afternoon, shall I say?`;
}
else if(hours > 12 && hours <= 16) {
document.getElementById("time").innerText = `Good Afternoon`;
} else if(hours > 16) {
document.getElementById("time").innerText = `Good Evening`;
}
document.getElementById("known").style.display = "block";
}
if(userName_cookie === undefined) {
noUserName();
} else {
userNameKnown();
}
#not-known {
display: block;
text-align: center;
font-size: 40px;
}
#not-known > input {
color: black;
font-size: 30px;
}
#submit-btn:hover {
cursor: pointer;
}
#known {
font-size: 40px;
text-align: center;
display: none;
}
<!-- Hello, What is your name -->
<div id="not-known">
<p>Hello, What is your name?</p>
<input type="text" placeholder="Enter your name here" id="enter-name">
<input type="button" value="submit" id="submit-btn">
</div>
<!-- If known -->
<div id="known">
<p id="hello">Hello,</p>
<p id="time">Good</p>
</div>
它在我的网站主页上,https://aaditya-baduni.github.io/.正如您在JS代码if(userName_cookie === undefined) {noUserName();}
的末尾所看到的,noUserName((函数似乎没有运行,因为我无法显示"known"div。
我必须将用户名保存为cookie。我想发生的事情-点击提交输入标签时,名称将注册为cookie,未知div的显示将设置为"none",已知div的显示设置为"block"(要运行的userNameKnown((函数(
在进入if
语句之前,读取cookie的代码将出错:
document.cookie.split("; ").find(row => row.startsWith("username")).split("=")[1];
如果.find()
没有检索到任何匹配项,它将返回undefined
,这意味着您正在调用undefined.split()
,这将导致错误。
解决这个问题的简单方法是使用条件链接:
document.cookie.split("; ").find(row => row.startsWith("username"))?.split("=")[1];
.split()
之前的?
检查它是否没有尝试调用undefined
上的函数,并将防止错误,并允许代码继续运行if语句。