簡體   English   中英

如何定位數組 object 中的 boolean 值。 JavaScript

[英]How to target boolean value in array object. JavaScript

 let myQuestions = [ { question: "What's 2+2?", answers: [ { text: "4", correct: true }, { text: "2", correct: false }, { text: "10", correct: false }, { text: "1", correct: false }, ], }, { question: "What's 10+10?", answers: [ { text: "20", correct: true }, { text: "2", correct: false }, { text: "18", correct: false }, { text: "0", correct: false }, ], }, ]; function showQuestion(questionAndAnswers) { const shuffledAnswers = _.shuffle(questionAndAnswers.answers); questionTag.innerText = questionAndAnswers.question; answerTag[0].innerText = shuffledAnswers[0].text; answerTag[1].innerText = shuffledAnswers[1].text; answerTag[2].innerText = shuffledAnswers[2].text; answerTag[3].innerText = shuffledAnswers[3].text; } document.querySelectorAll(".answer").forEach((correctAnswer) => { correctAnswer.addEventListener("click", (event) => { if (myQuestions.answers == true) { console.log("s"); } }); })

基本上,我的問題在一個數組中,答案也在 object 中,問題被放在屏幕上,答案被打亂了。 我需要幫助的是下面的最后一段代碼,如何檢查單擊的值是否為真(正確答案)。

 <h3 id="question"></h3> <div class="answers"> <button id="answer1" class="answer"></button> <button id="answer2" class="answer"></button> <button id="answer3" class="answer"></button> <button id="answer4" class="answer"></button> </div>

向答案標簽添加一個屬性,指示它是否是正確答案。 然后你可以在事件監聽器中檢查。

 let myQuestions = [ { question: "What's 2+2?", answers: [ { text: "4", correct: true }, { text: "2", correct: false }, { text: "10", correct: false }, { text: "1", correct: false }, ], }, { question: "What's 10+10?", answers: [ { text: "20", correct: true }, { text: "2", correct: false }, { text: "18", correct: false }, { text: "0", correct: false }, ], }, ]; function showQuestion(questionAndAnswers) { const shuffledAnswers = _.shuffle(questionAndAnswers.answers); questionTag.innerText = questionAndAnswers.question; questionAndAnswers.answers.forEach(({text, correct}, i) => { answerTag[i].innerText = text; answerTag[i].dataset.correct = correct; }; } document.querySelectorAll(".answer").forEach((answer) => { answer.addEventListener("click", (event) => { if (event.target.dataset.correct == 'true') { console.log("s"); } }); })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM