问题:
I am creating a quiz game using JavaScript and I want to create a function that check the answer if correct
My goal here is to check if button clicked among the 4 buttons...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
I am creating a quiz game using JavaScript and I want to create a function that check the answer if correct
My goal here is to check if button clicked among the 4 buttons is correct, need to identify the correct answer for each of the questions.
Can you guide me what to do?
I have the array of objects:
let myQuestions = [{
question: "How old is LJ?",
answers: {
a: "27",
b: "25",
c: "26",
d: "24",
correctAnswer: "b",
},
},
{
question: "What is her favorite game?",
answers: {
a: "ML",
b: "COD",
c: "DOTA 2",
d: "LOL",
correctAnswer: "b",
},
},
{
question: "Where does LJ live?",
answers: {
a: "Pasig city",
b: "Quezon city",
c: "Rizal",
d: "Sta Mesa",
correctAnswer: "a",
},
}
];
//Here's my JavaScript code function to render the question and the choices everytime we click the buttons.
function renderQuestion() {
let show = document.getElementById('question');
let q = myQuestions[questionIndex];
show.innerHTML = q.question;
questionIndex++;
console.log(questionIndex)
button1.innerHTML = q.answers.a;
button2.innerHTML = q.answers.b;
button3.innerHTML = q.answers.c;
button4.innerHTML = q.answers.d;
}
回答1:
Try this
Assuming this quiz is not important (anyone can see the answers in the source)
I moved the correctAnswer outside the list of answers
let myQuestions = [{ question: "How old is LJ?", answers: { a: "27", b: "25", c: "26", d: "24", }, correctAnswer: "b", }, { question: "What is her favorite game?", answers: { a: "ML", b: "COD", c: "DOTA 2", d: "LOL", }, correctAnswer: "b", }, { question: "Where does LJ live?", answers: { a: "Pasig city", b: "Quezon city", c: "Rizal", d: "Sta Mesa", }, correctAnswer: "a", } ];
let questionIndex = 0;
function renderQuestion() {
if (questionIndex >= myQuestions.length) return;
let show = document.getElementById('question');
let q = myQuestions[questionIndex];
show.innerHTML = q.question;
Object.entries(q.answers).forEach(([letter,text]) => {
const but = document.getElementById(letter);
but.innerHTML = text
but.dataset.correct = q.correctAnswer === letter;
})
questionIndex++;
}
renderQuestion()
document.getElementById("buts").addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.type && tgt.type === "button") {
document.getElementById("result").innerText = tgt.dataset.correct === "true" ? "Correct" : "Incorrect"
}
})
document.getElementById("next").addEventListener("click", renderQuestion)
<span id="question"></span> <span id="result"></span>
<div id="buts">
<button type="button" id="a"></ button>
<button type="button" id="b"></ button>
<button type="button" id="c"></ button>
<button type="button" id="d"></ button>
</div>
<button type="button" id="next">Next</button>