【问题标题】:Javascript true or false test won't output anythingJavascript真假测试不会输出任何东西
【发布时间】:2021-02-27 01:07:10
【问题描述】:

function sub() {
  var num1 = parseInt(document.getElementById("imp").value);
  var yes = "Yup!"
  var no = "Nope..."
  if (imp == "true") {
    output(yes);
  } else if (imp == "false") {
    output(no)
  }
}
    
function output(x) {
  document.getElementById("result").innerHTML = x;
}
body {
  background:green;
  background-repeat: no-repeat;
  background-size: cover;
  font-family: 'Roboto', sans-serif !important;
}
h1 {
  text-align: center;
  color: #ffffff;
  font-size: 4em;
  text-shadow: 4px 4px #000000;
}

p {
  text-align: center;
  color: #ffffff;
  font-size: 4em;
  text-shadow: 4px 4px #000000;
}
<p>TRUE OR FALSE</p>
<p>Polar bears have black skin.</p>
<input type="text" id="imp">
<button onclick="sub()">Submit</button>
<div id="result"></div>

【问题讨论】:

  • imp == "true" 不是imp HTMLInputElement?为什么那会是“真实的”?你的意思是num1
  • 天哪……我才意识到。是的,这就是我的意思。
  • 你应该学习如何使用调试器——它们可以快速发现这些“简单”的错误,而且每个人都会不时犯这些错误。 PS:我不知道这是不是你代码的所有问题,这只是我第一次卡住。

标签: javascript html output getelementbyid


【解决方案1】:

首先,您似乎是要检查 num1 的值,而不是 imp(它在您的代码中不存在,但它是您从中获取值的元素的名称)。我只是将变量名称更改为 userInput 以更清楚地说明您从用户那里得到的信息。

其次,您希望用户提供“真”或“假”字符串来进行检查,但您正试图将其转换为整数。删除parseInt()。我在末尾添加了toLowerCase(),以防止在用户使用任何大写字母('True'、'False'、'tRuE'、'fAlSe'等)的情况下出现错误。

最后,我建议在条件检查的末尾添加一个最终的 else 语句,作为用户未输入“真”或“假”的后备(如果您的 UI 始终是傻瓜式的,如果用户输入了任何异常或意外的内容)。

function sub() {
  var userInput = document.getElementById("imp").value.toLowerCase();
  var yes = "Yup!";
  var no = "Nope...";
  var idk = "Invalid input";

  if (userInput == "true") {
    output(yes);
  } else if (userInput == "false") {
    output(no);
  } else {
    output(idk);
  }
}
    
function output(x) {
  document.getElementById("result").innerHTML = x;
}
body {
  background:green;
  background-repeat: no-repeat;
  background-size: cover;
  font-family: 'Roboto', sans-serif !important;
}
h1 {
  text-align: center;
  color: #ffffff;
  font-size: 4em;
  text-shadow: 4px 4px #000000;
}

p {
  text-align: center;
  color: #ffffff;
  font-size: 4em;
  text-shadow: 4px 4px #000000;
}
<p>TRUE OR FALSE</p>
<p>Polar bears have black skin.</p>
<input type="text" id="imp">
<button onclick="sub()">Submit</button>
<div id="result"></div>

【讨论】:

  • 谢谢!我正在使用计算器脚本中的一些代码,我想我忘了更改一些东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-31
  • 1970-01-01
  • 1970-01-01
  • 2022-10-13
  • 2015-04-15
  • 1970-01-01
相关资源
最近更新 更多