简体   繁体   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

I have a trivia app that has four buttons, each with their own answer.我有一个有四个按钮的琐事应用程序,每个按钮都有自己的答案。 I have implemented getElementById for each button, and have also added "click" event listeners to each one.我已经为每个按钮实现了 getElementById,并且还为每个按钮添加了“click”事件侦听器。 Upon clicking the button, the function "checkAnswer" runs.点击按钮后,function“checkAnswer”运行。 This is what the function looks like so far.这是 function 到目前为止的样子。

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

"randomQuestion" and "answer" are global variables. “randomQuestion”和“answer”是全局变量。 randomQuestion generates a question from a pool of questions imported from a separate file. randomQuestion 从从单独文件导入的问题池中生成一个问题。

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

I need to find the correct answer and compare it to the selected answer.我需要找到正确的答案并将其与所选答案进行比较。 I think I might need to grab the index of each button, but I am unsure how to do that.我想我可能需要获取每个按钮的索引,但我不确定该怎么做。

Here is one question from my array of object questions.这是我的一系列 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 }
        ]
      },

The callback function for the addEventListener takes another parameter which we usually term as event . addEventListener 的回调 function 采用另一个我们通常称为event的参数。 You can make use of the parameter to distinguish which button is clicked.您可以使用该参数来区分单击了哪个按钮。

Below is the minimum reproducible example for the same.以下是相同的最小可重现示例。

NOTE: Please don't add same event listeners like I have added below in your production code.注意:请不要像我在您的生产代码中添加的那样添加相同的事件侦听器。 You can make use of the bubbling & capturing concept when in need of adding same listerner to multiple elements.当需要将相同的侦听器添加到多个元素时,您可以使用冒泡和捕获概念。

 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>

I got carried away and wrote a class .我得意忘形,写了一个class Here's what you need to know:以下是您需要了解的内容:

  • For each answer, make an attribute of the <button> , <input type='radio'> , etc. the value of question[x].answers[y].correct x from the outer loop and y from the inner loop.对于每个答案,将<button><input type='radio'>等的question[x].answers[y].correct x的值来自外部循环, y来自内部循环。 (see Figure I ) 见图一

    Figure I图一

    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; }); });

    You'll have buttons that have data-key attribute -- one of them is true the other three are false .您将拥有具有data-key属性的按钮——其中一个为true ,其他三个为false (see Figure II ) 见图二

    Figure II图二

    `<input type='button' value='${question[idx].answer[i].text}' data-key='${question[idx].answer[i].correct}' >`
  • Next, either bind the click event to each answer individually or to a parent element.接下来,将 click 事件单独绑定到每个答案或绑定到父元素。 (see Figure III and Figure IV ) 见图三图四

    Figure III图三

    <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>

    Figure IV图四

    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.

相关问题 如何检查单击按钮的答案以查看它是否与 JavaScript 中的一组对象中找到的正确答案相匹配,以进行琐事游戏 - How do I check the answer of a clicked button to see if it matches the correct answer found within an array of objects in JavaScript for a trivia game 如何处理我正在制作的琐事游戏的答案? (JavaScript) - How to process the answer on this trivia game I'm making? (Javascript) 如何为每个正确答案绘制简单图形 - How do i make a simple graph for each correct answer 只有在问答游戏中返回 true 的对象数组的第一个答案,而不是 Javascript 中的正确答案 - Only the first answer of an array of objects returning true in a trivia game, rather than the correct answer in Javascript 如何得到正确答案 - How to get correct answer Javascript测验-获取选定的单选按钮值并比较以得到正确答案 - Javascript Quiz - Get Selected Radio Button Value and Compare to Correct Answer 我如何显示答案是否正确 - How do i show if an answer is correct or not JS加法游戏:我如何显示4个可能的答案,其中3个是随机的,1个是正确的答案? (包括Codepen) - JS addition game: how do I display 4 possible answers, 3 of them are random and 1 is the correct answer ? (Codepen included) 如何检查已提交的单选按钮是否包含正确答案 - How to check whether submitted radio button contains the correct answer 单击检查答案按钮时如何使用 JavaScript 更改正确答案的颜色 - How to change the color of correct answer using JavaScript when check answer button clicked
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM