1
抱歉模糊/「個人」的問題。我很難弄清楚爲什麼我的代碼不能像我想要的那樣工作。從本質上講,我的程序是一款數學遊戲。我試圖做一個「重新測驗」的功能,這讓你重做數學問題,你錯了。如何讓我的功能按計劃工作?我的邏輯錯了嗎? (LONG)
所以我有一個函數調用另外:
function addition() { //addition function
function generateNumber() { //generateNumber is a function that creates 2 numbers based on the user's input from cookies
var n1= Math.floor(Math.random() * (cookiearray[2] - cookiearray[1]) + cookiearray[1]); //n1 is equal to a random number between the user input. It grabs values from the cookie array.
var n2= Math.floor(Math.random() * (cookiearray[2] - cookiearray[1]) + cookiearray[1]); //n2 is also a random number.
document.getElementById("question").innerHTML = n1 + " + " + n2 + "=" ; //this asks the user the question
window.answer = n1+n2;
} //end of generateNumber function
generateNumber(); //calls the generateNumber function.
}
此功能只是讓2張隨機數,並要求您添加它。現在,爲了讓計算機知道答案,我將它作爲一個稱爲「答案」的全局變量存儲答案。
然後,我用jQuery來評估答案。如果按下輸入鍵,則會檢查答案是否與用戶輸入的內容相同。如果是錯的,那麼計算機把這個問題放到一個數組,答案到另一個陣列的問題:
$("#input").keyup(function(event){ //targets the input box
if(event.keyCode == 13){ //when enter is pressed
if(answer == $('#input').val()){ //evaluate if the input value was equal to the global variable answer (from game.js)
//if it is the correct answer...
score += 1; //add score by 1
document.getElementById("score").innerHTML = "Score: " + score ; //print score
addition();
$('#input').val('') //clears text box for next question
}
else {
//if the input answer was incorrect...
requizQuestions.push(display1);
requizAnswers.push(answer);
document.getElementById("incorrect").innerHTML += "<br />" + "The answer to " + display1 + " was " + answer + " not " + $('#input').val();
addition();
$('#input').val('') //clears text box for next question
}
} //end if statement (with keycode)
無論哪種方式,當用戶得到正確/錯誤的,除了函數被再次調用。
現在,我的真正問題是如何顯示問題並使其「覆蓋」添加函數創建的內容(稱爲答案和問題的變量)。我應該如何創建一個這樣做的函數?我目前沒有這樣做的代碼...
function requiz() {
var i = 0;
window.answer = requizAnswers[i];
document.getElementById("question").innerHTML = requizQuestions[i];
$("#input").keyup(function(event){ //targets the input box
if(event.keyCode == 13){ //when enter is pressed
if(answer === $('#input').val()){ //evaluate if the input value was equal to the global variable answer (from game.js)
i+=1;
window.answer = requizAnswers[i];
document.getElementById("question").innerHTML = requizQuestions[i];
} else {
//didn't know what to put here
}
} //end if statement (with keycode)
});
}
謝謝你,Dave! – Edwin