如何让我的按钮将用户的答案与"correct"答案进行比较?



我正在尝试使我的第一个输入字段自动显示一个随机乘法和,然后用户应在第二个输入字段中回答该总和。然后,当用户单击按钮"检查我的答案",然后弹出窗口。出现在说"您做到了"或"错误!"时出现。ETC。另外,由于某种原因,当我删除空功能时,我的乘法总和停止工作!任何人都可以放光吗?

这是我的代码:

var x = Math.floor(Math.random() * 12) + 1;
var y = Math.floor(Math.random() * 12) + 1;
function genQuestion() {
    var Question = x + " times " + y;
    document.getElementById("inputVal").value = Question;
    return Question;
}
function genAnswer() {
    answer = x * y;
    return answer;
}
window.onload = genQuestion;
function buttonPressed() {
    var userAnswer = document.getElementById("outputVal").value;
    if (answer === userAnswer) {
        alert("Correct- Well Done!");
    }
    else {
        alert("Wrong- Please try again!");
    }
}
function d() {
}
<h1>Learn to Multiply Website</h1>
<form name="myForm" id="myForm" action="#">
    <label>What is</label>
    <input id="inputVal" name="inputVal" type="text"/>
    <br>
    <label>The answer is</label>
    <input name="outputVal" id="outputVal" type="text"/>
    <br>
    <button class="button" onclick="buttonPressed()">Check my Answer</button>
</form>

您正在使用 answer,n note.

您可以直接调用您对genAnswer的答案功能与问题进行比较

===更改为==以进行自动类型转换。

更新的代码

var x = Math.floor(Math.random() * 12) + 1;
var y = Math.floor(Math.random() * 12) + 1;
function genQuestion() {
  var Question = x + " times " + y;
  document.getElementById("inputVal").value = Question;
  return Question;
}
function genAnswer() {
  answer= x * y;
  return answer;
}
window.onload = genQuestion;
function buttonPressed(){
  var userAnswer = document.getElementById("outputVal").value;
  if (userAnswer == genAnswer()){
    alert("Correct- Well Done!");
  }
  else {alert("Wrong- Please try again!");}
}
function d(){}
<h1>Learn to Multiply Website</h1>
    <form name="myForm" id="myForm" action="#">
        <label>What is</label>
        <input id="inputVal" name="inputVal" type="text" />
        <br>
        <label>The answer is</label>
        <input name="outputVal" id="outputVal" type="text" />
        <br>
        
        <button class = "button" onclick="buttonPressed()">Check my Answer</button>
        
    </form>

if语句是无效的:

function buttonPressed() {
var userAnswer = document.getElementById("outputVal").value;
if (answer === userAnswer) {
    alert("Correct- Well Done!");
}

因为"答案"不是变量,所以它是函数" genanswer"返回的值。

所以您的" if"语句应该像这样:

If(genAnswer() == userAnswer){}

最新更新