未捕获的类型错误:无法读取 null 的属性“toLowerCase”

Uncaught TypeError: Cannot read property 'toLowerCase' of null

本文关键字:null 读取 属性 toLowerCase 类型 错误      更新时间:2023-09-26

这个提示在我更新其他一些javascript之前一直运行良好。我不知道我是怎么搞砸的。此函数在 body tag 中声明为运行"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();
}
}

现在突然我收到此错误,并且不会出现提示。

不确定为什么你会得到一个空,但如果你想避免空,请使用这个:

answer = (answer?answer:'').toLowerCase();

如果我们单击取消,提示将返回null并且不能在null上应用toLowerCase(会导致异常!

在所有其他条件之前添加一个条件answer===nullreturn以停止执行function

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();

在您的情况下,最好使用确认而不是提示

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();