2016-12-06 37 views
1

我有一個程序,隨機生成兩個數字(x和y),並要求用戶將它們相乘。一旦它們相乘,就會告訴它們是否正確或錯誤。我遇到的問題是,如果他們得到正確的答案,它應該生成一組新的數字。我不知道如何讓程序再次執行該功能。無論對錯,它都必須清除答案字段。謝謝!JavaScript如果答案正確,生成新的字符串

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); 
    } 
} 

回答

1

你沒有調用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 = ''; 
} 
+0

幫助了很多,謝謝! – rozak

相關問題