Estou estudando JavaScript, nível iniciante. Assim, estou tentando montar um quiz de acordo com um tutorial que encontrei mas encontro o seguinte erro ao executar:
["SyntaxError: expected expression, got '<'", "filename": "https://stacksnippets.net/js", "lineno": 45, "colno": 8]
Entendi que o problema é o tal <label>
, mas qual seria a forma correta de implementar, então?
var myQuestions = [
{
question:"Quem é o primeiro ministro do Reino Unido?",
answers: {
a:"David Cameron",
b:"Gordon Brown",
c:"Winston Churchill",
d:"Tony Blair"
},
correctAnswer:"d"
},
{
question:"Quem descobriu o Brasil?",
answers: {
a:"Pedro Álvares Cabral",
b:"Cristovao Colombo",
c:"Floriano Peixoto",
d:"Jorge Amado",
},
correctAnswer:"a"
}
];
function buildQuiz(){
var output = [];
myQuestions.forEach((currentQuestion, questionNumber) => {
const answers = [];
for (letter in currentQuestion.answers) {
answers.push(
<HTMLLabelElement>
<input type="radio" name="questions${questionNumber}" value="${letter}">
${letter} :
${currentQuestion.answers[letter]}
</HTMLLabelElement>
);
}
output.push(
<div class="question"> ${currentQuestion.question} </div>
<div class="answers"> ${answers.join('')} </div>
);
});
quizContainer.innerHTML = output.join('');
};
function showResults(){
const answerContainers = quizContainer.querySelectorAll('.answers');
let numCorrect = 0
myQuestions.forEach( (currentQuestion, questionNumber) => {
// find selected answer
const answerContainer = answerContainers[questionNumber];
const selector = 'input[name=question'+questionNumber+']:checked';
const userAnswer = (answerContainer.querySelector(selector) || {}).value;
// if answer is correct
if(userAnswer===currentQuestion.correctAnswer){
// add to the number of correct answers
numCorrect++;
// color the answers green
answerContainers[questionNumber].style.color = 'lightgreen';
}
// if answer is wrong or blank
else{
// color the answers red
answerContainers[questionNumber].style.color = 'red';
}
});
// show number of correct answers out of total
resultsContainer.innerHTML = numCorrect + ' out of ' + myQuestions.length;
}
// display quiz right away
buildQuiz();
// on submit, show results
submitButton.addEventListener('click', showResults);