我正在使用JavaScript進行測驗,並且我被困在如何完成計算得分上。目前在控制檯中,用戶響應被推送爲一個名爲userAnswer的數組,其值爲true或false。從這裏開始,我很難計算出如何計算答案的真實數量,並在測試結束時顯示得分。Javascript測驗得分
非常感謝您的幫助!
$(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>
使用'var score = 0;'而不是'console.log(true)'set'score ++;'。那是你在找什麼? – instead
app.js是我們應該關注的問題還是僅僅是OP中已有的jQuery? – zer00ne