简体   繁体   English

当我点击按钮时,问题没有进入下一个

[英]Question is not advancing to the next one when I click the button

When I click the button, the question is not advancing to the next one after choosing an answer from the given option.当我单击该按钮时,从给定选项中选择一个答案后,问题不会进入下一个问题。 I can't identify the problem but the getStarted function is working because I tested it by console.logging the answer.我无法确定问题,但getStarted函数正在工作,因为我通过 console.logging 答案对其进行了测试。 Please, what could be wrong?请问,可能有什么问题? I am new at JavaScript, have been trying to solve it for two days now, will be very grateful if it's solved.我是 JavaScript 新手,已经尝试解决两天了,如果解决了,将不胜感激。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Quiz</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    
    <div class="container">
        <div class="quiz-section">
            <h1 id="question">Questions</h1>

            <ul>
                <li>
                    <input type="radio" name="answer" class="answer">
                    <label for="a" id="a-text">Question</label>
                </li>
                <li>
                    <input type="radio" name="answer" class="answer"> 
                    <label for="b" id="b-text">Question</label>
                </li>
                <li>
                    <input type="radio" name="answer" class="answer"> 
                    <label for="c" id="c-text">Question</label>
                </li>
                <li>
                    <input type="radio" name="answer" class="answer"> 
                    <label for="d" id="d-text">Question</label>
                </li>
            </ul>
        </div>
        <button id="submit">submit</button>
    </div>
    

    <script src="script.js"></script>
</body>
</html>
const questionA = document.getElementById('a-text')
const questionB = document.getElementById('b-text')
const questionC = document.getElementById('c-text')
const questionD = document.getElementById('d-text')
const QuestionEl = document.getElementById('question')
const submitEl = document.getElementById('submit')
const answerEl = document.querySelectorAll('.answer')

const quizData = [{
    question: 'whats is the most use programming language in 2021?',
    a: 'python',
    b: 'javascript',
    c: 'java',
    d: 'c',
    correct: 'b'
  },
  {
    question: 'in what year was javascript found?',
    a: '2003',
    b: '1992',
    c: '1995',
    d: '2000',
    correct: 'c'
  },
  {
    question: 'who is the ceo of facebook?',
    a: 'mark',
    b: 'jack',
    c: 'daniel',
    d: 'elon',
    correct: 'a'
  },
  {
    question: 'how old is emmanuel uzoezie?',
    a: '28',
    b: '20',
    c: '25',
    d: '23',
    correct: 'd'
  },
  {
    question: 'is javascript is the oldest progaramming language?',
    a: 'yes',
    b: 'no',
    c: 'all of the above',
    d: 'none of the above',
    correct: 'b'
  }
];

let currentQuiz = 0;

loadQuiz();

function loadQuiz() {
  const questionQuizData = quizData[currentQuiz]

  QuestionEl.innerHTML = questionQuizData.question
  questionA.innerHTML = questionQuizData.a
  questionB.innerHTML = questionQuizData.b
  questionC.innerHTML = questionQuizData.c
  questionD.innerHTML = questionQuizData.d
}

function getStartded() {
  let answers = undefined;
  answerEl.forEach((answer) => {
    if (answer.checked) {
      answers = answer.id;
    }
  })
  return answers;
}

submitEl.addEventListener('click', () => {
  const answer = getStartded();
  if (answer) {
    currentQuiz++;
    loadQuiz();
  }
})

The issue is in this line in your getStartded() function:问题出在getStartded()函数中的这一行:

answers = answer.id;

Your answer object (which is your radio button input) does not contain an id property, so when you return answers;您的答案对象(这是您的单选按钮输入)不包含id属性,因此当您return answers; , the value is always undefined. ,该值始终未定义。

Since it's undefined, you never get inside the if of your event listener.由于它未定义,因此您永远不会进入事件侦听器的if

Edit: You can fix this by, for example, putting an id property on your inputs...编辑:例如,您可以通过在输入上放置 id 属性来解决此问题...

I hope its works.我希望它的作品。 You should return answers after fill it.您应该在填写后返回答案。 On the next question answer will be empty.下一个问题的答案将为空。

function getStartded() {
  let answers = undefined;
  answerEl.forEach((answer) => {
    if (answer.checked) {
      answers = answer;
    }
  })
return answers;
}

submitEl.addEventListener('click', () => {
  const answer = getStartded();
  if (answer) {
    answer.checked = false; 
    currentQuiz++;
    loadQuiz();
  }
})

Let's review the relevant part of your code:让我们回顾一下代码的相关部分:

let currentQuiz = 0;

loadQuiz();

function loadQuiz() {
  // note: it's advisable to use semicolons after a line of code
  const questionQuizData = quizData[currentQuiz]

  QuestionEl.innerHTML = questionQuizData.question
  // innerHTML is not necessary here 
  // because the values are pure text
  // textContent is sufficient and less risky
  // (see https://medium.com/@jenlindner22/the-risk-of-innerhtml-3981253fe217)
  questionA.innerHTML = questionQuizData.a
  questionB.innerHTML = questionQuizData.b
  questionC.innerHTML = questionQuizData.c
  questionD.innerHTML = questionQuizData.d
}

function getStartded() {

  // you are using [type=radio] input elements, so only
  // one item will be checked. This checked answer
  // can be queried using the css selector
  // ".answer:checked"
  // Now, if you add values (a - d) to these inputs
  // you can read the checked value directly as
  // document.querySelector(".answer:checked").value

  let answers = undefined;
  answerEl.forEach((answer) => {
    if (answer.checked) {
      answers = answer.id;
      // in your html the .answer elements don't have an id
      // so 'answers' will stay undefined
    }
  })
  return answers;
}

// If you use event delegation, you don't really need a button.
// See the suggested code from the snippet.
submitEl.addEventListener('click', () => {
  const answer = getStartded();
  //             ^ see comment above
  //             ^ the value of answer will always be undefined
  if (answer) {
    // because answer is undefined, this code will
    // never be reached.
    currentQuiz++;
    loadQuiz();
  }
})

I would suggest a somewhat different approach, aggregating the questions in html beforehand using a .hidden class to hide the not yet answered questions and event delegation for the click -handling.我会建议一种稍微不同的方法,使用.hidden类预先聚合 html 中的问题来隐藏尚未回答的问题和click事件委托

Something like:就像是:

 // use event delegation document.addEventListener(`click`, evt => { if (evt.target.id === `redo`) { document.querySelector(`#allquestions`).textContent = ``; return createQuestions(); } if (evt.target.closest(`[data-qid]`)) { return score(evt); } }); createQuestions(); // score handler function score(evt) { const inp = evt.target.closest(`[data-qid]`); const checkedAnswer = inp.querySelector(`[type=radio]:checked`); if (checkedAnswer) { const response = checkedAnswer.dataset.answer; const currentQuestion = getQuizData([inp.dataset.qid]); const resultOk = checkedAnswer.value === currentQuestion.correct; const report = inp.querySelector(`[data-result]`); !resultOk && report.classList.add(`notOk`); report.dataset.result = `${response}: ${resultOk ? `bang on!` : `nope, sorry...`}`; inp.querySelectorAll(`input`).forEach(el => el.remove()); const nextQuestion = document.querySelector(`[data-qid='${ +inp.dataset.qid + 1}']`); if (nextQuestion) { nextQuestion.classList.toggle(`hidden`); } } } // aggregate question data into html function createQuestions() { const data = getQuizData(); const questionsElem = document.querySelector(`#allquestions`); data.forEach((q, i) => questionsElem.insertAdjacentHTML( `beforeend`, `<div data-qid="${i}" class="${i > 0 ? `hidden` : ``}"> <div>${q.question}</div> ${Object.entries(q) .filter( ([key, value]) => key.length === 1) .map( ([k, v]) => `<input type="radio" name="answer" value="${k}" data-answer=${v}>` ) .join(``)} <span data-result></span> </div>`)); } function getQuizData(forQuestion) { const questions = [{ question: 'What is the most used programming language in 2021?', a: 'python', b: 'javascript', c: 'java', d: 'c', correct: 'b' }, { question: 'In what year was javascript founded?', a: '2003', b: '1992', c: '1995', d: '2000', correct: 'c' }, { question: 'Who is the CEO of facebook?', a: 'mark', b: 'jack', c: 'daniel', d: 'elon', correct: 'a' }, { question: 'How old is Emmanuel Uzoezie?', a: '28', b: '20', c: '25', d: '23', correct: 'd' }, { question: 'Is javascript the oldest programming language?', a: 'yes', b: 'no', correct: 'b' } ]; return forQuestion ? questions[forQuestion] : questions; }
 body { font: normal 12px/15px verdana, arial, sans-serif; margin: 2rem; } .hidden { display: none; } [data-qid] { margin-bottom: 0.8rem; } [data-qid] div:nth-child(1) { font-weight: bold; } [data-result].notOk { color: red; } [data-result] { color: green; } [data-result]:before { content: attr(data-result); } input[type=radio] { display: block; margin: 3px 0 3px 0; } input[type=radio]:after { content: attr(data-answer); margin-left: 24px; }
 <div class="container"> <div class="quiz-section"> <h1 id="question">Questions</h1> <div id="allquestions"></div> </div> <button id="redo">Redo</button> </div>

See also 也可以看看

answer.id is not assigned attributes, you need to add id=option to each radio element, for example: answer.id没有分配属性,需要给每个radio元素加上id=option ,例如:

<div class="quiz-section">
        <h1 id="question">Questions</h1>

        <ul>
            <li>
                <input type="radio" name="answer" class="answer" id="a">
                <label for="a" id="a-text">Question</label>
            </li>
            <li>
                <input type="radio" name="answer" class="answer" id="b"> 
                <label for="b" id="b-text">Question</label>
            </li>
            <li>
                <input type="radio" name="answer" class="answer" id="c"> 
                <label for="c" id="c-text">Question</label>
            </li>
            <li>
                <input type="radio" name="answer" class="answer" id="d"> 
                <label for="d" id="d-text">Question</label>
            </li>
        </ul>
    </div>
    <button id="submit">submit</button>
</div>

Another solution, update this snippet code.另一个解决方案,更新这个片段代码。

html html

<div class="container">
    <div class="quiz-section">
        <h1 id="question">Questions</h1>

        <ul>
            <li>
                <input type="radio" name="answer" class="answer" value="a">
                <label for="a" id="a-text">Question</label>
            </li>
            <li>
                <input type="radio" name="answer" class="answer" value="b"> 
                <label for="b" id="b-text">Question</label>
            </li>
            <li>
                <input type="radio" name="answer" class="answer" value="c"> 
                <label for="c" id="c-text">Question</label>
            </li>
            <li>
                <input type="radio" name="answer" class="answer" value="d"> 
                <label for="d" id="d-text">Question</label>
            </li>
        </ul>
    </div>
    <button id="submit">submit</button>
</div>

javascript javascript

function getStartded() {
   let checkedEl = document.querySelector('.answer:checked');
   return checkedEl ? checkedEl.value : undefined;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 单击下一步按钮时问题索引未更新 - Question index not updating when I click next button 当我点击下一个按钮时,上一个问题必须用反向 animation 删除,下一个问题必须显示输入效果 animation - When i click on next button, the previous question must be remove with reverse animation & next question must be show with typing effect animation 如何在不单击下一步按钮的情况下进入下一个问题? - How can I go for next question without click next button? 我有 5 个问题。 当我单击下一个按钮时,我希望下一个问题显示在 h2 元素中 - I have an array of 5 questions. When I click the next button, I want the next question to be shown in the h2 element 当我单击按钮时加载下一行 - Load next row when i click the button 我使用 .off() 限制一次点击。 但是当下一页按钮不起作用时 - i use .off() limit one click . but when next page button not work 我需要在点击按钮上播放下一首歌 - I need to play next song when click on on-click button 当我单击下一步按钮时如何更改活动阶段 - How to change active stage when i click on next button 当我在 VueJS 中单击下一个或上一个按钮时显示一个列表 - Display a list when i click next or previous button in VueJS 当我单击 gliderjs 中的下一个/上一个按钮时,页面 go 到顶部 - Page go to top when i click on next/prev button in gliderjs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM