我如何在JavaScript类别中分组答案?

时间:2018-03-12 10:02:03

标签: javascript html

目前,我正在为我的信息通信技术学士学位和教育学士学位毕业。因此,我正在进行一次“测验”,在此基础上,可以评估学生在21世纪技能新能力方面的进展。

我在SitePoint (https://www.sitepoint.com/simple-javascript-quiz/)上阅读了Yaphi Berhanu的一篇很棒的文章,它可以在屏幕上打印问题并存储正确答案的数量。

对于这个项目,我需要添加变量'category'来存储特定类别的正确答案数量。

直到今天我将代码调整到一个测验,该测验将结果存储在6个不同的隐藏输入值中。但它仍然没有将结果存储在正确的类别中。 “未捕获的ReferenceError:未定义类别”

我如何/在哪里定义'category'变量?

代码片段如下:

(function() {
  const myQuestions = [{
      question: "",
      category: "1",
      answers: {
        a: "Superman",
        b: "The Terminator",
        c: "Waluigi, obviously"
      },
      correctAnswer: "c"
    },
    {
      question: "",
      category: "2",
      answers: {
        a: "SitePoint",
        b: "Simple Steps Code",
        c: "Trick question; they're both the best"
      },
      correctAnswer: "c"
    },
    {
      question: "",
      category: "3",
      answers: {
        a: "Antarctica",
        b: "Exploring the Pacific Ocean",
        c: "Sitting in a tree",
        d: "Minding his own business, so stop asking"
      },
      correctAnswer: "c"
    },
    {
      question: "",
      category: "4",
      answers: {
        a: "Antarctica",
        b: "Exploring the Pacific Ocean",
        c: "Sitting in a tree",
        d: "Minding his own business, so stop asking"
      },
      correctAnswer: "c"
    },
    {
      question: "",
      category: "5",
      answers: {
        a: "Antarctica",
        b: "Exploring the Pacific Ocean",
        c: "Sitting in a tree",
        d: "Minding his own business, so stop asking"
      },
      correctAnswer: "c"
    },
    {
      question: "",
      category: "6",
      answers: {
        a: "Antarctica",
        b: "Exploring the Pacific Ocean",
        c: "Sitting in a tree",
        d: "Minding his own business, so stop asking"
      },
      correctAnswer: "c"
    }
  ];

  function buildQuiz() {
    // we'll need a place to store the HTML output
    const output = [];


    // for each question...
    myQuestions.forEach((currentQuestion, questionNumber) => {
      // we'll want to store the list of answer choices
      const answers = [];

      // here we store the questioncategory
      const category = [];

      // and for each available answer...
      for (letter in currentQuestion.answers) {
        // ...add an HTML radio button
        answers.push(
          `<label>
             <input type="radio" name="question${questionNumber}" value="${letter}">
              ${letter} :
              ${currentQuestion.answers[letter]}
           </label>`
        );
      }

      // add this question and its answers to the output
      output.push(
        `<div class="slide">
           <div class="question"> ${currentQuestion.question} </div>
           <div class="answers"> ${answers.join("")} </div>
         </div>`
      );
    });

    // finally combine our output list into one string of HTML and put it on the page
    quizContainer.innerHTML = output.join("");
  }

  function showResults() {
    // gather answer containers from our quiz
    const answerContainers = quizContainer.querySelectorAll(".answers");

    // keep track of user's answers
    let numCorrect1 = 0;
    let numCorrect2 = 0;
    let numCorrect3 = 0;
    let numCorrect4 = 0;
    let numCorrect5 = 0;
    let numCorrect6 = 0;

    // for each question...
    myQuestions.forEach((currentQuestion, questionNumber) => {
      // find selected answer
      const answerContainer = answerContainers[questionNumber];
      const selector = `input[name=question${questionNumber}]:checked`;
      const userAnswer = (answerContainer.querySelector(selector) || {}).value;

      // if answer is correct
      if (userAnswer === currentQuestion.correctAnswer) {
        // add to the number of correct answers
        if (category === 1) {
          numCorrect1++;
        }
        if (category === 2) {
          numCorrect2++;
        }
        if (category === 3) {
          numCorrect3++;
        }
        if (category === 4) {
          numCorrect4++;
        }
        if (category === 5) {
          numCorrect5++;
        }
        if (category === 6) {
          numCorrect6++;
        }

        // color the answers green
        answerContainers[questionNumber].style.color = "lightgreen";
      } else {
        // if answer is wrong or blank
        // color the answers red
        answerContainers[questionNumber].style.color = "red";
      }
    });

    // show number of correct answers out of total
    resultsContainer1.value = `${numCorrect1}`;
    resultsContainer2.value = `${numCorrect2}`;
    resultsContainer3.value = `${numCorrect3}`;
    resultsContainer4.value = `${numCorrect4}`;
    resultsContainer5.value = `${numCorrect5}`;
    resultsContainer6.value = `${numCorrect6}`;
  }

  function showSlide(n) {
    slides[currentSlide].classList.remove("active-slide");
    slides[n].classList.add("active-slide");
    currentSlide = n;

    if (currentSlide === 0) {
      previousButton.style.display = "none";
    } else {
      previousButton.style.display = "inline-block";
    }

    if (currentSlide === slides.length - 1) {
      nextButton.style.display = "none";
      previousButton.style.display = "none";
      submitButton.style.display = "inline-block";
    } else {
      nextButton.style.display = "inline-block";
      submitButton.style.display = "none";
    }
  }

  function showNextSlide() {
    showSlide(currentSlide + 1);
  }

  function showPreviousSlide() {
    showSlide(currentSlide - 1);
  }

  const quizContainer = document.getElementById("quiz");
  const resultsContainer1 = document.getElementById("results1");
  const resultsContainer2 = document.getElementById("results2");
  const resultsContainer3 = document.getElementById("results3");
  const resultsContainer4 = document.getElementById("results4");
  const resultsContainer5 = document.getElementById("results5");
  const resultsContainer6 = document.getElementById("results6");
  const submitButton = document.getElementById("submit");

  // display quiz right away
  buildQuiz();

  const previousButton = document.getElementById("previous");
  const nextButton = document.getElementById("next");
  const slides = document.querySelectorAll(".slide");
  let currentSlide = 0;

  showSlide(0);

  // on submit, show results
  submitButton.addEventListener("click", showResults);
  previousButton.addEventListener("click", showPreviousSlide);
  nextButton.addEventListener("click", showNextSlide);
})();
.question {
  font-size: 0px;
  margin-bottom: 0px;
}

.answers {
  margin-bottom: 0px;
  text-align: left;
  display: inline-block;
}

.answers label {
  display: block;
  margin-bottom: 0px;
}

.slide {
  position: absolute;
  left: 0px;
  top: 0px;
  width: 100%;
  z-index: 1;
  opacity: 0;
  transition: opacity 0.5s;
}

.active-slide {
  opacity: 1;
  z-index: 2;
}

.quiz-container {
  position: relative;
  height: 100px;
  margin-top: 0px;
}
<div class="quiz-container">
  <div id="quiz"></div>
</div>
<button class="w3-button w3-block w3-blue w3-section w3-padding w3-half" type="button" id="previous"><i class="fa fa-angle-left"></i> Vorige</button>
<button class="w3-button w3-block w3-blue w3-section w3-padding w3-half" type="button" id="next">Volgende <i class="fa fa-angle-right"></i></button>
<button class="w3-button w3-block w3-blue w3-section w3-padding" type="button" id="submit" name="submit">Verzenden</button>
<input id="results1" type="hidden" name="1" value="">
<input id="results2" type="hidden" name="2" value="">
<input id="results3" type="hidden" name="3" value="">
<input id="results4" type="hidden" name="4" value="">
<input id="results5" type="hidden" name="5" value="">
<input id="results6" type="hidden" name="6" value="">
<input type="hidden" name="usrname" value="">

1 个答案:

答案 0 :(得分:1)

参考错误通常很容易找到:您使用的是未在代码中声明的变量/对象。

罪魁祸首在于您的category方法,以下代码段应该有效。我已将currentQuestion.category更改为 function showResults() { // ... myQuestions.forEach((currentQuestion, questionNumber) => { const answerContainer = answerContainers[questionNumber]; const selector = `input[name=question${questionNumber}]:checked`; const userAnswer = (answerContainer.querySelector(selector) || {}).value; // if answer is correct if (userAnswer === currentQuestion.correctAnswer) { // add to the number of correct answers if (currentQuestion.category == 1) { numCorrect1++; } if (currentQuestion.category == 2) { numCorrect2++; } if (currentQuestion.category == 3) { numCorrect3++; } if (currentQuestion.category == 4) { numCorrect4++; } if (currentQuestion.category == 5) { numCorrect5++; } if (currentQuestion.category == 6) { numCorrect6++; } // color the answers green answerContainers[questionNumber].style.color = "lightgreen"; } else { // if answer is wrong or blank // color the answers red answerContainers[questionNumber].style.color = "red"; } }); // ... }

另外,尝试对代码进行标准化,现在阅读起来很奇怪。你可以互换地使用匿名函数和普通for循环,使用注释来澄清“坏”变量名等,Style Guides可以帮助你解决这个问题。

{{1}}

相关问题