【发布时间】:2022-02-13 20:31:33
【问题描述】:
我正在创建一个测验,我尝试在正确时将答案按钮变为绿色,在不正确时将答案按钮变为红色,然后保存此信息并转到下一个问题。但是目前的代码不起作用。这是我的 JavaScript 代码:
let shuffledQuestions, currentQuestionIndex;
const setNextQuestion = () => {
showQuestion(shuffledQuestions[currentQuestionIndex]);
}
const showQuestion = (gameData) => {
questionElement.innerText = gameData.question;
let answersBlock = '';
gameData.answer.forEach((answer, index) => {
const answerButton = `
<div class="answers-wrapper col-lg-6 col-md-6 col-lg-3">
<button class="btn answer-button" id="answersbutton-${index + 1}" onclick="selectAnswer()">
${answer.text}
</button>
</div>
`;
answersBlock += answerButton;
});
answerButtonsElement.innerHTML = answersBlock;
}
const selectAnswer = (e) => {
const selectedButton = e.target;
const correct = selectedButton.dataset.correct;
setStatusClass(document.body, correct);
Array.from(answerButtonsElement.children).forEach(button => {
setStatusClass(button, button.dataset.correct);
})
}
function setStatusClass(element, correct) {
clearStatusClass(element);
if (correct) {
element.classList.add('correct');
} else {
element.classList.add('wrong');
}
}
function clearStatusClass(element) {
element.classList.remove('correct');
element.classList.remove('wrong');
}
const gameData = [
{
question: 'What is the smallest country in the world?',
answer: [
{ text: 'Vatican City', correct: true },
{ text: 'Malta', correct: false },
{ text: 'Italy', correct: false },
{ text: 'Monaco', correct: false }
]
},
【问题讨论】:
-
什么不起作用?您是否使用浏览器中的开发工具进行了所有调试?你有错误吗?
-
不要将答案结果存储到
data-*属性中。将它们存储在您的 gameData 中。 -
是的,这是一个错误:script.js:131 Uncaught TypeError: Cannot read properties of undefined (reading 'target') at selectAnswer (script.js:131:30) at HTMLButtonElement.onclick (index .html:1:1)
标签: javascript html css