Как добавить открытые вопросы с помощью текстового поля Javascript - PullRequest
0 голосов
/ 02 августа 2020

Я хочу изменить следующий код, который я нашел, и добавить вопросы с учебником или полем, которые пользователь может заполнить ответом вместо только множественного выбора. Однако каждый раз, когда я пытаюсь добавить, если код поврежден или нет. Я скопировал код и удалил все, кроме трех вопросов. как я могу это изменить?

var quizzes = [
  {
    name: "test",
    questions: [
      {
        text: "Test1?",
        choices: [
          { text: "1", correct: false },
          { text: "2", correct: true },
          { text: "3", correct: false },
        ],
      },
      {
        text: "test2",
        choices: [
          { text: "4", correct: false },
          { text: "5", correct: false },
          { text: "6", correct: true },
        ],
      },
      {
        text: "Test3",
        choices: [
          { text: "7", correct: true },
          { text: "8", correct: false },
          { text: "9", correct: false },
        ],
      },
      {
    ]
  

// When the document is ready
window.addEventListener('DOMContentLoaded', function() {
  var $container = document.getElementById('container');
  // Initialize each quiz into the container
  quizzes.forEach(function(quiz) { initQuiz(quiz, $container); });
});

function initQuiz(quiz, $container) {
  // DOM elements
  var $dom = initDOM(quiz, $container),
  // Current question index (starts at 0)
      num = 0,
      score = 0;
  
  nextScreen();
  
  function nextScreen() {
    if (num < quiz.questions.length) {
      displayQuestion();
    } else {
      displayEndResult();
    }
  }
  
  function displayQuestion() {
    clearDisplayArea();
    var question = quiz.questions[num];
    
    // Display the image if there is one
    if (question.image) {
      $dom.display.innerHTML = '<img src="' + question.image + '" class="question-img"/>';
    }
    // Display the question
    $dom.display.innerHTML +=
        '<p>Q' + (num+1) + ': ' + question.text + '</p>'
      + question.choices.map(function(choice, i) {
         return '<label>'
              +   '<input type="radio" name="' + quiz.name + '" value="' + i + '"/>'
              +   choice.text
              + '</label>';
       return  '<form>'
              +   '<input type = "text" id="textbook" name="'  + quiz.name + '" value="' + i + '"/>'
              +   textbox.text  
              + '</form>' ;
       }).join('')
      + '<br>';
    
    // Create Submit button
    $submit = document.createElement('button');
    $submit.addEventListener('click', onAnswerSubmit);
    $submit.innerHTML = 'Submit';
    // Add the submit button
    $dom.display.appendChild($submit);
  }
  
  function onAnswerSubmit() {
    // Get the checked radio button
    var selectedChoice = $dom.display.querySelector('input:checked');
    if (!selectedChoice) {
      alert("You need to select an answer");
    } else {
      // If it's correct
      if (quiz.questions[num].choices[selectedChoice.value].correct) {
        score++; // Add 1 point to the score
      }
      num++;
      nextScreen();
    }
  }
  
  function displayEndResult() {
    clearDisplayArea();
    $dom.display.innerHTML = '<p>End of Quiz</p>'
                    + '<p>Congratulations! Your score is: ' + score + '</p>'
                    + '<p>If you scored lower than 2, please keep practicing</p>';
  }
  
  function clearDisplayArea() {
    $dom.display.innerHTML = '';
  }

  // The "DOM" (Document Object Model) represents HTML elements
  function initDOM(quiz, $container) {
    // Create frame

1 Ответ

0 голосов
/ 02 августа 2020
  1. Итак, это одно из решений, сначала убедитесь, что у вас есть поле ввода в вашем файле html.
  2. Теперь с полем ввода вы можете дать ему класс того, что вы хотите, как показано ниже
<input class="personAnswer"></input>
Теперь вы можете go вернуться к своему JS коду и добавить следующий
document.getElementById("personAnswer").(WHATEVER YOU WANT TO CHECK FOR)

И все!

...