簡體   English   中英

當我點擊按鈕時,問題沒有進入下一個

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

當我單擊該按鈕時,從給定選項中選擇一個答案后,問題不會進入下一個問題。 我無法確定問題,但getStarted函數正在工作,因為我通過 console.logging 答案對其進行了測試。 請問,可能有什么問題? 我是 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();
  }
})

問題出在getStartded()函數中的這一行:

answers = answer.id;

您的答案對象(這是您的單選按鈕輸入)不包含id屬性,因此當您return answers; ,該值始終未定義。

由於它未定義,因此您永遠不會進入事件偵聽器的if

編輯:例如,您可以通過在輸入上放置 id 屬性來解決此問題...

我希望它的作品。 您應該在填寫后返回答案。 下一個問題的答案將為空。

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

我會建議一種稍微不同的方法,使用.hidden類預先聚合 html 中的問題來隱藏尚未回答的問題和click事件委托

就像是:

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

也可以看看

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>

另一個解決方案,更新這個片段代碼。

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

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

暫無
暫無

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

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