gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 15:56:54 25 4
gpt4 key购买 nike

我试图让我的第一个输入字段自动显示一个随机乘法和,然后用户应该在第二个输入字段中回答该和。然后,当用户单击“检查我的答案”按钮时,会出现一个弹出窗口,提示“你做到了”或“错了!” 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

你可以直接调用你的answer函数给genAnswer来和question比较

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

更新代码

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>

关于javascript - 如何让我的按钮将用户答案与 "correct"答案进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40958293/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com