未捕获的类型错误:无法读取 null 的属性“toLowerCase”
2016-04-28
22103
在我更新其他 javascript 之前,此提示一直运行良好。我不知道我是怎么搞砸它的。此函数在 body 标签中声明为运行“onload”。
function funcPrompt() {
var answer = prompt("Are you a photographer?", "Yes/No");
answer = answer.toLowerCase();
if (answer == "yes") {
alert('Excellent! See our links above and below to see more work and find contact info!');
}
else if(answer == "no") {
alert('That is okay! See our links above and below to learn more!');
}
else if(answer == null || answer == "") {
alert('Please enter an answer.');
funcPrompt();
}
else {
alert('Sorry, that answer is not an option');
funcPrompt();
}
}
现在我突然收到此错误,并且提示不会出现。
3个回答
不确定为什么会得到 null,但是如果您想避免 null,请使用以下命令:
answer = (answer?answer:'').toLowerCase();
vivekagarwal277
2020-06-18
如果我们点击
取消
,提示将返回
null
,并且不能对
null
应用
toLowerCase
(将导致异常!)
在所有其他条件之前添加条件
answer===null
,然后
return
以停止
函数
的执行
function funcPrompt() {
var answer = prompt("Are you a photographer?", "Yes/No");
if (answer === null || answer === "") {
alert('Please enter an answer.');
funcPrompt();
return;
}
answer = answer.toLowerCase();
if (answer == "yes") {
alert('Excellent! See our links above and below to see more work and find contact info!');
} else if (answer == "no") {
alert('That is okay! See our links above and below to learn more!');
} else {
alert('Sorry, that answer is not an option');
funcPrompt();
}
}
funcPrompt();
Rayon
2016-04-28
对于您来说,最好使用确认而不是提示
function funcConfirm() {
var answer = confirm("Are you a photographer?");
if (answer === true) {
alert('Excellent! See our links above and below to see more work and find contact info!');
} else {
alert('That is okay! See our links above and below to learn more!');
}
}
funcConfirm();
Yordan Ivanov
2016-04-28