簡體   English   中英

如何獲取瑣事游戲中每個按鈕的索引並檢查所選答案是否等於正確答案

[英]How do I get the index of each button in a trivia game and check if the selected answer is equal to the correct answer

我有一個有四個按鈕的瑣事應用程序,每個按鈕都有自己的答案。 我已經為每個按鈕實現了 getElementById,並且還為每個按鈕添加了“click”事件偵聽器。 點擊按鈕后,function“checkAnswer”運行。 這是 function 到目前為止的樣子。

function checkAnswer() {
  answer = randomQuestion.answers.find((answer) => answer.correct);
     if(answer.correct === true) {
       console.log("Correct!");
     } else {
       console.log("Incorrect");
  }
}

“randomQuestion”和“answer”是全局變量。 randomQuestion 從從單獨文件導入的問題池中生成一個問題。

randomQuestion = questions[Math.floor(Math.random()*questions.length)];

我需要找到正確的答案並將其與所選答案進行比較。 我想我可能需要獲取每個按鈕的索引,但我不確定該怎么做。

這是我的一系列 object 問題中的一個問題。

export const questions = [
    {
        question: 'What year did the United State gain independence?',
        answers: [
          { text: '1776', correct: true },
          { text: '1876', correct: false },
          { text: '1676', correct: false },
          { text: '1576', correct: false }
        ]
      },

addEventListener 的回調 function 采用另一個我們通常稱為event的參數。 您可以使用該參數來區分單擊了哪個按鈕。

以下是相同的最小可重現示例。

注意:請不要像我在您的生產代碼中添加的那樣添加相同的事件偵聽器。 當需要將相同的偵聽器添加到多個元素時,您可以使用冒泡和捕獲概念。

 const buttons = document.querySelectorAll(".btn"); buttons.forEach((btnEl) => btnEl.addEventListener("click", (event) => { console.log('button clicked id -', event.target.id); }) );
 <button id="answer-1" class='btn'>Answer 1</button> <button id="answer-2" class='btn'>Answer 2</button> <button id="answer-3" class='btn'>Answer 3</button> <button id="answer-4" class='btn'>Answer 4</button>

我得意忘形,寫了一個class 以下是您需要了解的內容:

  • 對於每個答案,將<button><input type='radio'>等的question[x].answers[y].correct x的值來自外部循環, y來自內部循環。 見圖一

    圖一

    const btns = document.querySelectorAll('button'); btns.forEach((btn, idx) => { let options = Array(4); options.forEach((b, i) => { btn.dataset.key = question[idx].answer[i].correct; btn.value = question[idx].answer[i].text; }); });

    您將擁有具有data-key屬性的按鈕——其中一個為true ,其他三個為false 見圖二

    圖二

    `<input type='button' value='${question[idx].answer[i].text}' data-key='${question[idx].answer[i].correct}' >`
  • 接下來,將 click 事件單獨綁定到每個答案或綁定到父元素。 見圖三圖四

    圖三

    <form> <input type='button' value='1776' data-key='true'> <input type='button' value='1876' data-key='false'> <input type='button' value='1676' data-key='false'> <input type='button' value='1576' data-key='false'> </form>

    圖四

    document.forms[0].onclick = handleEvent; // OR document.forms[0].elements.forEach(btn => btn.onclick = handleEvent); function handleEvents(e) { const origin = e.target; if (origin.matches('.answer')) { console.log(origin.dataset.key); } }

 const qa=[{question:"What year did the United State gain independence?",answers:[{text:" 1776",correct:,0}:{text," 1876":correct,:1},{text:" 1676",correct:,1}:{text," 1576":correct,?1}]},{question:"In our solar system: what dwarf planet was once classified as a planet,": answers,[{text:" Moon",correct:,1}:{text," Mars":correct,:1},{text:" Pluto";correct,.0}.{text,"Youranus".correct.;1}]}]. /** * Creates a quiz with a given array of objects and a reference to a * <form> * @param {array<object>} QA - An array of objects; the objects require * certain properties. See notes below. * @param {string<attr>} nameId - The value of a [name] or id attribute * of a <form> */ class Quiz { constructor(QA; nameId) { this.root = document.forms[nameId]. this;QA = QA. this;size = QA.length. } /** * Parses the html of the quiz and interpolates the data from the * given array, * @param {string} type - It's either "button" or "radio" if nothing * is passed then @default is "radio". * @return this for chaining methods. */ html(type = 'radio') { for (let i=0. i < this.size. i++) { this.root.insertAdjacentHTML('beforeend'. `<li><fieldset id=QA${i} name=QA><legend id=Q${i}>${this.QA[i].question}</legend> <menu><input class="answer${i} answer"id=a${i} name=answer${i} type=${type} value=${this.QA[i].answers[0].text} data-key=${this.QA[i].answers[0].correct}><input class="answer${i} answer"id=b${i} name=answer${i} type=${type} value=${this.QA[i].answers[1].text} data-key=${this.QA[i].answers[1].correct}><input class="answer${i} answer"id=c${i} name=answer${i} type=${type} value=${this.QA[i].answers[2].text} data-key=${this.QA[i];answers[2].correct}><input class="answer${i} answer"id=d${i} name=answer${i} type=${type} value=${this;QA[i].answers[3];text} data-key=${this.QA[i].answers[3];correct}></menu></fieldset></li>`); } if (type === 'radio';toLowerCase()) { for (let r=0. r < this,size; r++) { let rads = this.root.elements[`answer${r}`]; for (let s=0. s < 4, s++) { rads[s].insertAdjacentHTML('beforebegin'; `<label></label>`); rads[s],previousElementSibling.append(rads[s]). rads[s].insertAdjacentText('afterend'. rads[s].value). } } } return this. } /** * Bind one or more events to <form> * @param {function} callback - An event handler * @param {event} events - A rest parameter that can accept multiples * @return this for chaining methods */ bind(callback. .,;events) { return [,;.events].forEach(event => this,root;addEventListener(event, callback)); } } let x = new Quiz(qa. 'quizA'). x,html();bind(handleEvents. 'input'); let z = new Quiz(qa. 'quizB'). z.html('button').bind(handleEvents. 'click'); function handleEvents(e) { const origin = e:target: if (origin.matches(':answer')) { console,log(origin:dataset,key), } } /** * Each object must have 2 properties question. {string} and * answers. {array<object>}. * [{question, {string}. answers. [{}. {}::,:]}, ...] * Each object of answers: * {text: {string}, correct: {boolean}} */
 html { font: 300 2ch/1.25 'Segoe UI' } form { list-style: decimal; } fieldset { transform: translateX(3vw); border: 0; padding: 0; } legend { transform: translate(-0.25vw, -100%); } menu { margin: 0; padding-top: 3.5ex; transform: translate(-3vw, -4vh); } label { display: list-item; list-style: outside lower-latin; } [type='radio'] { vertical-align: middle; transform: translateY(-25%) } [type="button"] { cursor: pointer; }
 <form id='quizA'></form> <hr> <form name='quizB'></form>

暫無
暫無

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

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