首页 > 解决方案 > 带有文本输入选项的 JS 交互式测验

问题描述

我是编码新手,所以请耐心等待,因为我没有软件工程师或 CS 专业人士的专业知识。

我将使用 Javascript、Html 和 css 在网站上进行交互式测验。到目前为止,我看到的所有示例都是表单,带有单选输入选项的问题,以及在 JS 其他地方表达的答案。我想知道的是,如果没有明确的答案,是否可以有一个文本输入答案部分而不是无线电输入部分?

以下是我试图模仿的例子。这是来自 codepen 的 SitePoint 的代码。

https://codepen.io/SitePoint/pen/GmPjjL

(function() {
  const myQuestions = [{
      question: "Who is the strongest?",
      answers: {
        a: "Superman",
        b: "The Terminator",
        c: "Waluigi, obviously"
      },
      correctAnswer: "c"
    },
    {
      question: "What is the best site ever created?",
      answers: {
        a: "SitePoint",
        b: "Simple Steps Code",
        c: "Trick question; they're both the best"
      },
      correctAnswer: "c"
    },
    {
      question: "Where is Waldo really?",
      answers: {
        a: "Antarctica",
        b: "Exploring the Pacific Ocean",
        c: "Sitting in a tree",
        d: "Minding his own business, so stop asking"
      },
      correctAnswer: "d"
    }
  ];

  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 = [];

      // 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 numCorrect = 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
        numCorrect++;

        // 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
    resultsContainer.innerHTML = `${numCorrect} out of ${myQuestions.length}`;
  }

  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";
      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 resultsContainer = document.getElementById("results");
  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);
})();
@import url(https://fonts.googleapis.com/css?family=Work+Sans:300,600);
body {
  font-size: 20px;
  font-family: 'Work Sans', sans-serif;
  color: #333;
  font-weight: 300;
  text-align: center;
  background-color: #f8f6f0;
}

h1 {
  font-weight: 300;
  margin: 0px;
  padding: 10px;
  font-size: 20px;
  background-color: #444;
  color: #fff;
}

.question {
  font-size: 30px;
  margin-bottom: 10px;
}

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

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

button {
  font-family: 'Work Sans', sans-serif;
  font-size: 22px;
  background-color: #279;
  color: #fff;
  border: 0px;
  border-radius: 3px;
  padding: 20px;
  cursor: pointer;
  margin-bottom: 20px;
}

button:hover {
  background-color: #38a;
}

.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: 200px;
  margin-top: 40px;
}
<html>

<body>
  <h1>Quiz on Important Facts</h1>
  <div class="quiz-container">
    <div id="quiz"></div>
  </div>
  <button id="previous">Previous Question</button>
  <button id="next">Next Question</button>
  <button id="submit">Submit Quiz</button>
  <div id="results"></div>
</body>

</html>

标签: javascriptjqueryhtmlcss

解决方案


这就是你想要的?https://codepen.io/fiter92/pen/RwbdNog

现在您必须在问题数组中写下正确答案:

const myQuestions = [
  {
    question: "The right answer is Superman",
    correctAnswer: "Superman" // here is a correct answer string
  }
]

现在你的 answerdiv元素得到了correctincorrect类名,所以你可以根据需要自定义样式:

// if answer is correct
if (userAnswer.trim().toUpperCase() == currentQuestion.correctAnswer.trim().toUpperCase()) {
  // add to the number of correct answers
  numCorrect++;

  // add correct class name
  answerContainers[questionNumber].classList.remove("incorrect");
  answerContainers[questionNumber].classList.add("correct");
} else {
  // if answer is wrong or blank
  // add incorrect class name
  answerContainers[questionNumber].classList.remove("correct");
  answerContainers[questionNumber].classList.add("incorrect");
}

推荐阅读