【发布时间】:2019-07-05 06:07:30
【问题描述】:
我对 Web 开发很陌生,这是我的第一个项目。我正在尝试使用数组创建一个测验来显示问题、选择和答案。我已经成功地在网页上显示了问题和选择。但我仍然无法显示用户选择或获取选定的单选按钮。我必须这样做,这样我才能在这个测验中显示分数。
HTML:
<!DOCTYPE Html>
<html>
<head>
</head>
<body>
<div id="quiz"></div>
<button id="button">Done!</button>
<script src="scripts.js"></script>
</body>
</html>
Javascript:
var myQuestions = [
['1. Which sentence uses "famish" correctly?', "After the straight exam, I
felt too exhausted and famished to eat my favourite foods.", "I could eat a
horse, I am famish now.", "I famished my stomach next time you treat me to a
meal out.", "I will bring lots of pizza, that's a famish.", "a"],
["2. Priscila _______ rather not invest her savings in the stock market.",
"must", "has to", "could", "would", "d"],
["3. Did you have any problem ______ our house?", "search", "to search",
"searching", "for searching", "c"],
/*********************************************************************/
var quiz_id = document.getElementById('quiz');
var submitButton = document.getElementById("button");
/*********************************************************************/
myQuestions.forEach(function(myQuestions){
quiz_id.innerHTML += `
<div>${myQuestions[0]} <br></div>
<form>
<label>
<input class="answers" type="radio" name="choices"
value="a">${myQuestions[1]}<br/>
<input class="answers" type="radio" name="choices"
value="b">${myQuestions[2]}<br/>
<input class="answers" type="radio" name="choices"
value="c">${myQuestions[3]}<br/>
<input class="answers" type="radio" name="choices"
value="d">${myQuestions[4]}<br/>
</label>
</form>
`;
});
/*********************************************************************/
function showResults(){
//1. set the total score
var total = 0;
//2. show the correct answer
myQuestions.forEach(function(myQuestions, index){
var correctAnswer = myQuestions[5];
quiz_id.innerHTML += `<div>correct answer for number ${index} :
${correctAnswer}</div>`;
});
//3. show the user their answer
var choice = document.getElementsByName('choices');
var userChoice;
for(var i = 0; i < choice.length; i++){
if(choice[i].checked){
userChoice = choice[i].value;
}
quiz_id.innerHTML += `${userChoice}`;
}
//4. if the user choice matches the correct answer add a score to total
variable
if(userChoice === correctAnswer){
total++;
}
//5. display the scores
quiz_id.innerHTML = `<div>You have scored a total of ${total}</div>`;
}
/*********************************************************************/
submitButton.addEventListener("click", showResults);
在函数showResults()中
我在使用 3 号和 4 号时遇到了问题。
【问题讨论】:
标签: javascript html arrays foreach radio-button