我有一个程序,可以随机生成两个数字(x 和 y)并要求用户将它们相乘。一旦他们将它们相乘,它就会告诉他们是对还是错。我遇到的问题是,如果他们得到正确的答案,它应该生成一组新的数字。我不确定如何让程序再次执行该功能。此外,无论他们答对还是错,它都必须清除答案字段。谢谢!
var x, y; // global variables for randomly generated numbers
var correct = ['Very good!', 'Excellent!', 'Correct - Nice work!', 'Correct - Keep up the good work!'];
var incorrect = ['No. please try again.', 'Wrong. Try once more.', 'Incorrect - Dont give up!', 'No - Keep trying.'];
// getting two random numbers between 1-12 then assigning them to x and y
function generateNumbers() {
function aNumber() {
return Math.floor((Math.random() * 12) + 1);
}
x = aNumber();
y = aNumber();
}
// generating the question that will be used with the random numbers x and y
function genQuestion() {
generateNumbers();
document.getElementById('question').value = x + " times " + y;
}
// function that is performed when the button "check answer" is clicked. It will generate one of 4 answers depending
//if it's right or wrong and will add 1 to the value of total. If it's incorrect it won't add anything
function buttonPressed() {
var correctans = correct[Math.floor(Math.random() * 4)]; // randomly selecting an answer if it's correct
var incorrectans = incorrect[Math.floor(Math.random() * 4)]; // randomly selecting an answer if it's incorrect
var answer = document.getElementById('answer').value;
if (answer == x * y) // correct
{
function genQuestion() {
generateNumbers();
document.getElementById('question').value = x + " times " + y;
}
window.alert(correctans);
var total = document.getElementById('total').value++;
}
else { // incorrect
window.alert(incorrectans);
}
}
最佳答案
您没有调用 genQuestion 函数,重新定义它没有什么意义。
// function that is performed when the button "check answer" is clicked. It will generate one of 4 answers depending
//if it's right or wrong and will add 1 to the value of total. If it's incorrect it won't add anything
function buttonPressed() {
var correctans = correct[Math.floor(Math.random() * 4)]; // randomly selecting an answer if it's correct
var incorrectans = incorrect[Math.floor(Math.random() * 4)]; // randomly selecting an answer if it's incorrect
var answer = document.getElementById('answer').value;
if (answer == x * y) // correct
{
//call genQuestion to create new question
genQuestion();
window.alert(correctans);
var total = parseInt(document.getElementById('total').value)++;
}
else { // incorrect
window.alert(incorrectans);
}
//clear 'answer' field
document.getElementById('answer').value = '';
}
关于JavaScript 如果答案正确,则生成新字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41005622/