这会运行一个生成数学加法问题的if语句,我有一个输入询问用户他们想要完成多少个问题,但是当它运行时它会同时生成所有问题,而不是等待用户回答第一个问题然后清除innerHTML。有没有办法阻止它立即生成它们并等待使用if语句正确回答问题?
if(equation == "Addition(+)"){
number = document.getElementById('problems').value;
for(var i = 0; i<number; i++){
var inputedanswer =
document.getElementById('answerfield').value;
//Creates addition problem
a = Math.floor((Math.random() * 20) + 1);
b = Math.floor((Math.random() * 20) + 1);
if(inputedanswer == null){
//Trying to make it run only once
var answer = (parseInt(a) + parseInt(b));
//Creates question using the Math Random above
var p = document.createElement('p');
var text = document.createTextNode(a + " + " + b + " = ")
p.appendChild(text);
document.getElementById('question').appendChild(p);
//Creates radio buttons for answers
var select = document.createElement('input');
var submit = document.createElement('button');
document.getElementById('answerfield').appendChild(select);
document.getElementById('submit').appendChild(submit);
submit.innerHTML = "Check Answer";
//Submitting answer and checks if it is correct
submit.onclick = function(){
if(select.value != answer){
alert("I am sorry but that is not the correct answer, Please try again!");
}
else{
alert("That's correct!");
document.getElementById('field').innerHTML = "";
//Ask Erickson
}
}
}
}
}
答案 0 :(得分:0)
我怀疑你能用一种方法做到这一点。您应该将其拆分为连接到特定事件侦听器的不同方法(请参阅下面的列表)。 在我看来,用户应该得到一个问题列表来回答?当他回答一个时,应将其标记为正确或错误。
这个程序怎么样:
1)询问用户他想回答多少问题
- &GT;点击“开始测试”
2)根据用户的输入准备一些问题,将它们保存在一个数组中(一项=任务+答案+解决方案)
3)将所有问题解析为HTML
- &GT;检查何时给出答案,是否正确,显示结果
当然,您可以根据需要更改此程序。您还可以询问所请求问题的数量,将其保存为变量,然后始终生成问题,将其显示为HTML,等待答案(按钮单击),检查答案,显示解决方案,继续下一个问题,直到有足够的问题被展示了。
无论你做什么,使用多种方法并仅在用户做某事时调用它们(例如,点击按钮或给出答案)
答案 1 :(得分:-1)
将它放入一个函数中然后一旦他回答问题就调用函数。
if(he answers the question) {
waitForQuestion();
}
function waitForQuestion(){
if(equation == "Addition(+)"){
number = document.getElementById('problems').value;
for(var i = 0; i<number; i++){
var inputedanswer =
document.getElementById('answerfield').value;
//Creates addition problem
a = Math.floor((Math.random() * 20) + 1);
b = Math.floor((Math.random() * 20) + 1);
if(inputedanswer == null){
//Trying to make it run only once
var answer = (parseInt(a) + parseInt(b));
//Creates question using the Math Random above
var p = document.createElement('p');
var text = document.createTextNode(a + " + " + b + " = ")
p.appendChild(text);
document.getElementById('question').appendChild(p);
//Creates radio buttons for answers
var select = document.createElement('input');
var submit = document.createElement('button');
document.getElementById('answerfield').appendChild(select);
document.getElementById('submit').appendChild(submit);
submit.innerHTML = "Check Answer";
//Submitting answer and checks if it is correct
submit.onclick = function(){
if(select.value != answer){
alert("I am sorry but that is not the correct answer, Please try again!");
}
else{
alert("That's correct!");
document.getElementById('field').innerHTML = "";
//Ask Erickson
}
}
}
}
}
}