[英]Checking an input against a specific array string
我正在嘗試創建一個從陣列中的問題池中隨機選擇一個問題的測驗,將在輸入框中進行回答,該輸入框將根據陣列中的相應答案字符串進行檢查。 我用math.floor(math.random()*); 得到我的隨機數。 隨機數旨在用於查找問題和答案,它們被安排為彼此對應,例如['question1','question2']和['answer1','answer2']。
我很難嘗試根據數組中的相應答案值正確檢查我的輸入。 我是Java語言的新手,因此不確定如何執行此操作。 我嘗試使用document.getElementById命令比較兩者。 我懷疑這與ansNum無法獲得questNum的值有關,因為questNum僅在generateQuiz函數中獲得了它的值。 (我意識到ansNum可能是多余的,但我只是在玩耍看看是否會發生任何事情)
Javascript:
const questions = ['What do young Roman males wear?','Who is the Roman god of the smith?','Who is the 6th king of Rome?'];
const answers = ['toga praetexta','vulcan','servius tullius'];
function getQuestNum() {
questNum = Math.floor(Math.random() * 3);
};
function getAnsNum() {
ansNum = questNum();
}
function generateQuiz() {
getQuestNum();
document.getElementById("question").innerHTML = questions[questNum];
};
function checkCorrect() {
getAnsNum();
if (answer[ansNum] = document.getElementById("input").innerHTML) {
document.getElementById("verification").innerHTML = "Correct!";
}
};
創建一個同時包含一個問題和一個答案的對象數組,並創建一個生成隨機數並在相應索引處返回對象的函數,會更簡單。
然后,您將可以訪問所需的所有內容,而不必擔心是否可以訪問原始隨機選擇的數字,還是可以在兩個不同的數組之間匹配索引。
根據您的代碼,我通過一些更改對其進行了修復。 我認為這不是最好的方法。 我在這里發布了js部分。
const questions = ['What do young Roman males wear?','Who is the Roman god of the smith?','Who is the 6th king of Rome?'];
const answers = ['toga praetexta','vulcan','servius tullius'];
var questNum;
function getQuestNum() {
questNum = Math.floor(Math.random() * 3);
};
function getAnsNum() {
ansNum = questNum;
}
function generateQuiz() {
getQuestNum();
document.getElementById("question").innerHTML = questions[questNum];
};
function checkCorrect() {
getAnsNum();
if (answers[ansNum] = document.getElementById("input").value) {
document.getElementById("verification").innerHTML = "Correct!";
}
};
首先,您需要一個全局變量questNum,然后可以在所有函數中使用它。
函數getAnsNum()是多余的,至少我認為是這樣,只需在您的checkCorrect()函數中使用questNum即可。
對於getElementByID函數,在輸入中插入一個ID屬性
<input id="input" type="text" name="input">
對於輸入,如果要獲取輸入字段的值,請使用document.getElementById(“ input”)。value代替innerHTML。
如果不確定任何結果,請console.log它或使用Chrome dev調試工具檢查結果。 在checkCorrect函數中,您的數組名稱應該是答案而不是答案。
短版:
const questions = ['What do young Roman males wear?','Who is the Roman god of the smith?','Who is the 6th king of Rome?'];
const answers = ['toga praetexta','vulcan','servius tullius'];
var questNum;
function getQuestNum() {
questNum = Math.floor(Math.random() * 3);
};
function generateQuiz() {
getQuestNum();
document.getElementById("question").innerHTML = questions[questNum];
};
function checkCorrect() {
if (answers[questNum] = document.getElementById("input").value) {
document.getElementById("verification").innerHTML = "Correct!";
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.