我正在使用Javascript进行测验,我仍然坚持如何完成计算得分。目前在控制台中,用户响应被推送为名为userAnswer的数组的true或false。从这里我无法弄清楚如何计算出多少答案是真实的,并在测试结束时显示得分。
提前感谢您的帮助!
$(document).ready(function() {
var allQuestions = [{
question: 'What was the album of the year?',
choices: ['to Pimp a Butterfly', '1989', 'Traveller', 'Sound and Color'],
correctAnswer: '1989'
}, {
question: 'Who won best new artist?',
choices: ['Sam Smith', 'Tori Kelly', 'James Bay', 'Meghan Trainor'],
correctAnswer: 'Meghan Trainor'
}, {
question: 'What was the best dance recording?',
choices: ['Where Are U Now', 'Go', 'Never Catch Me', 'Runaway (U&I)'],
correctAnswer: 'Where Are U Now'
}, {
question: 'What won the best Country Album?',
choices: ['Montevallo', 'The Blase', 'Traveller', 'Pain Killer'],
correctAnswer: 'Traveller'
}];
var userAnswers = [];
function score() {
userAnswers(true)
}
//Reference to tags
var questionTitle = $("#questionTitle");
var selectionList = $("#selectionList");
var nextButton = $(".next");
//Initiating some variables
var questionNumber = 0;
var correctAnswer = undefined;
var userChoice = undefined;
$(".next").click(function() {
if (userChoice === allQuestions[questionNumber].correctAnswer) {
userAnswers.push(true);
console.log(true);
} else {
userAnswers.push(false);
console.log(false);
}
questionNumber++;
populateQuestion(questionNumber);
console.log(userAnswers);
});
function populateQuestion(qNum) {
$(questionTitle).empty();
$(selectionList).empty();
$(questionTitle).append(allQuestions[qNum].question);
for (var i = 0; i < allQuestions[qNum].choices.length; i += 1) {
console.log(i);
$(selectionList).append("<li>" + allQuestions[qNum].choices[i] + "</li>")
}
}
$("ul").on("click", "li", function() {
userChoice = $(this).text();
console.log(userChoice);
});
$(questionTitle).append(allQuestions[questionNumber].question);
for (var i = 0; i < allQuestions[questionNumber].choices.length; i += 1) {
console.log(i);
$(selectionList).append("<li>" + allQuestions[questionNumber].choices[i] + "</li>")
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<TITLE>2016 Grammy Quiz</TITLE>
<meta charset="utf-8"/>
<link href='https://fonts.googleapis.com/css?family=Lato:400,700,900,900italic' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div id = 'container'>
<h1> 2016 Grammy Quiz</h1>
<h2 id='questionTitle'> </h2>
<ul id ='selectionList'> </ul>
<button type="button" class = 'next'> Next </button>
</div>
<script src="http://code.jquery.com/jquery.min.js"></script>
<script src="js/app.js"></script>
</body>
</html>
答案 0 :(得分:0)
@instead的评论说你可以定义一个名为score
的变量,如果答案是正确的,你可以将得分增加1(使用score++
),否则将其减1(使用score--
)。最后,您可以使用document.write()
方法发布分数或引用HTML元素,并将其innerHTML
元素设置为总分。