Как я могу отобразить варианты ответов для моего опроса?

#javascript #html #object #survey

#javascript #HTML #объект #опрос

Вопрос:

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

Вот ссылка на мою IDE, поскольку я подумал, что будет проще пройти через нее, чтобы выявить любые ошибки, которые я совершаю: https://repl.it/@AS11RA/Forest-Firefighters-Website#index.html

Вот начало questionnaire.js файл:

 function buttonClicked(button) {
  button.style.visibility = "hidden";
  startSurvey();
  console.log("Survey started.");
}

function startSurvey() {

  var i;
  var j;
  var k;
  for (i = 0; i < ourQuestions.length; i  ) {
    document.getElementById("questions").innerHTML  = '<form id="question">Q'   (i   1)   ': '   ourQuestions[i].question;

    for (j = 0; j < ourQuestions[i].answers.length; j  ) {
      document.forms[i].innerHTML  = '</div><div class="answer"><input name="q1" value="'   ourQuestions[i].answers[j]   '" id="value4" type="checkbox" />'   ourQuestions[i].answers[j]   '<br/>';
    }
    document.getElementById("questions").innerHTML  = '</form><br/><br/>';
  }

  document.getElementById("questions").innerHTML  = '<button class="button" onclick="solveQuiz()">Solve Quiz</button>';

}

var ourQuestions = [{
    question: 'While naturally occurring wildfires can benefit ecosystems, unnatural blazes started by uncaring and negligent humans can do great harm and cause many deaths. What percentage of wildfires do you think are started by humans?',
    answers: {
      a: '10-15%',
      b: '85-90%',
      c: '45-50%',
      d: '25-30%'
    },
    correctAnswer: 'b'
  },
  {
    question: 'If you have lit a campfire before, how did you extinguish it?',
    answers: {
      a: 'I did not extinguish it and waited for it to die on its own',
      b: 'I extinguished the campfire with a bucket of water and made sure it was fully extinguished.',
      c: 'I have never lit a campfire before.',
      d: 'uhhh'
    },
    correctAnswer: 'b'
  },
  {
    question: 'What are the two most common reasons that forest fires start?',
    answers: {
      a: 'Lightning and human negligence',
      b: 'Spontaneous combustion and erosion',
      c: 'Animals igniting flames and overcrowded bushlands',
      d: 'Strong Wind Patterns'
    },
    correctAnswer: 'a'
  },
  {
    question: 'What time of the year do most forest fires occur?',
    answers: {
      a: 'Summer',
      b: 'Spring',
      c: 'Fall',
      d: 'Winter'
    },
    correctAnswer: 'a'
  },
  {
    question: 'How fast do you think forest fires spread?',
    answers: {
      a: '10.8 km/h',
      b: '6.4 km/h',
      c: '22.2 km/h',
      d: '3.2 km/h'
    },
    correctAnswer: 'a'
  },
  {
    question: 'What do forest fires need in order to burn?',
    answers: {
      a: 'Water',
      b: 'High humidity',
      c: 'Fuel',
      d: 'Clear weather'
    },
    correctAnswer: 'c'
  },
  {
    question: 'What is one of the main toxic gases present in forest fire smoke?',
    answers: {
      a: 'Osmium tetroxide',
      b: 'Disulfur decafluoride',
      c: 'Tungsten hexafluoride ',
      d: 'carbon monoxide'
    },
    correctAnswer: 'd'
  },
  {
    question: 'What natural disasters could be caused as a consequence of a destructive forest fire?',
    answers: {
      a: 'Erosion, flash flooding and landslides',
      b: 'Tornadoes',
      c: 'Snow',
      d: 'Tsunami and earthquakes'
    },
    correctAnswer: 'a'
  },
  {
    question: 'What major factor determines a forest fire’s behaviour?',
    answers: {
      a: 'Amount of water vapour in air',
      b: 'Density of Forests',
      c: 'Wind',
      d: 'Hours of sunlight'
    },
    correctAnswer: 'c'
  },
  {
    question: 'What 3 things are needed to start a fire?',
    answers: {
      a: 'Matches, oxygen, wood',
      b: 'Air and sunlight',
      c: 'Fuel, heat, oxygen',
      d: 'Fuel, oxygen, wood'
    },
    correctAnswer: 'c'
  },
  {
    question: 'Which one of these is NOT a type of forest fire?',
    answers: {
      a: 'Crown',
      b: 'Firework',
      c: 'Surface',
      d: 'Ground '
    },
    correctAnswer: 'b'
  },
  {
    question: 'What was the cause of the Amazon forest fires in 2019?',
    answers: {
      a: 'Deforestation for agriculture usage',
      b: 'Fireworks',
      c: 'Unattended campfire',
      d: 'Arson'
    },
    correctAnswer: 'a'
  },
  {
    question: 'Which one of these names are NOT an alternate name for forest fires?',
    answers: {
      a: 'Wildfires',
      b: 'Shrub fires',
      c: 'Natural fireworks',
      d: 'Brushfires '
    },
    correctAnswer: 'c'
  },
  {
    question: 'How many forest fires occurred in 2019?',
    answers: {
      a: '25 653',
      b: '50 477',
      c: '45 809',
      d: '89 431'
    },
    correctAnswer: 'b'
  }
];



function solveSurvey() {
  var x;
  var txt = ' ';
  var i = 0;
  var correct = 0;
  for (i = 0; i < document.forms.length; i  ) {
    x = document.forms[i];
    for (j = 0; j < x.length; j  ) {
      if (x[j].checked) {
        correctAnswer = ourQuestions[i].correctAnswer;
        if (x[j].value == ourQuestions[i].answers[correctAnswer]) {
          correct  = 1;
        }
      }
    }
      document.forms[i].innerHTML  = '</div><div class="answer"><input name="q1" value="'   ourQuestions[i].answers[j]   '" id="value4" type="radio" />'   ourQuestions[i].answers[j]   '<br/>';
  }
  document.getElementById("questions").innerHTML  = 'Correct answers: '   correct;
  

}
  

Вот анкета.HTML-файл:

 <!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Forest Firefighters: Questionnaire</title>
    <link href="survey style.css" rel="stylesheet" type="text/css" />
    <link href="main style.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.13.0/css/all.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="script.js" type="text/javascript"></script>
    <script src="start questionnaire.js" type="text/javascript"></script>
  </head>
  
  <body>
    <!--────────────────Header───────────────-->
      <header>
          <nav> 
            <ul class="nav-bar"><div class="bg"></div>
                <li><a class="nav-link" href="about.html">About</a></li>
                <li><a class="nav-link" href="index.html">Home</a></li>
                <li><a class="nav-link active" href="questionnaire.html">Questionnaire</a></li>
              <li><a class="nav-link" href="learning more.html">Learning more</a></li>
          <li><a class="nav-link" href="">Ways you can help</a></li>
            </ul>
          </nav>
      </header>

    <main>
        <!--─────────────────Home────────────────-->
        <div id="home">
            <div class="filter"></div>

        <!--────questionnaire button─────-->        
        <button class="button" onclick="buttonClicked(this)">Start Questionnaire</button>
        <spacer></spacer>
        <div id="questions"></div>
        <spacer></spacer>
        <spacer></spacer>
        </div>
    
      
          <div class="citing">
        <a class="citing-link" href=questionnaire.html">Image Source: https://phys.org/news/2019-11-countries-forest.html</a>
      <div>      
      </main>  

    <!--─────────────────Footer────────────────-->
      <footer class="copyright">© 2020 Amber, Aatiqah, Selina</footer>
  </body>

</html>
  

Ответ №1:

Причина, по которой ваши ответы не отображаются, заключается в том, что вы пытаетесь перебирать ответы, как будто это массив. Однако ответы — это объект, а не массив, поэтому вы не можете делать такие вещи, как использование ответов.свойство длины и т. Д.

Однако, вместо преобразования ваших ответов в массив, на самом деле есть более простой способ справиться с этим. То есть использовать цикл for …of с object.entries для объекта ourQueuestions.answers. Используя метод Object.entries(ourQuestions.answers), вы сможете извлекать ответы в парах «ключ» и «значение» и легко использовать их в цикле без классического цикла for, переменных i и j и т. Д.

Кроме того, вы ссылались на метод solviQuiz() в приведенном ниже блоке кода, однако в вашем коде имя этого метода на самом деле solveSurvey(), а не solviQuiz() . Итак, я тоже изменил это в приведенном ниже коде:

 document.getElementById('questions').innerHTML  =
    '<button class="button" onclick="solveSurvey()">Solve Quiz</button>';
}
  

Наконец, я бы рекомендовал вам прочитать о функциях ES6 из MDN docs, такие вещи, как циклические и строковые литералы for …of, были введены в ES6 в Javascript еще в 2015 году, и они упростят вашу жизнь как разработчика, использующего JS 🙂

Возможности MDN ES6

удачи! Вы можете напрямую использовать приведенный ниже код и убедиться, что он успешно отображает ответы в пользовательском интерфейсе.

 function buttonClicked(button) {
  button.style.visibility = 'hidden';
  startSurvey();
  console.log('Survey started.');
}

function startSurvey() {
  var i;
  var j;
  var k;
  for (i = 0; i < ourQuestions.length; i  ) {
    document.getElementById('questions').innerHTML  =
      '<form id="question">Q'   (i   1)   ': '   ourQuestions[i].question;
    debugger;
    for (let [key, value] of Object.entries(ourQuestions[i].answers)) {
      document.forms[i].innerHTML  =
        '</div><div class="answer"><input name="q1" value="'  
        value  
        '" id="value4" type="checkbox" />'  
        `${key}: '${value}'`; //use a string literal, makes a dev's life very easy
      ('<br/>');
    }
    document.getElementById('questions').innerHTML  = '</form><br/><br/>';
  }

  document.getElementById('questions').innerHTML  =
    '<button class="button" onclick="solveSurvey()">Solve Quiz</button>';
}

var ourQuestions = [
  {
    question:
      'While naturally occurring wildfires can benefit ecosystems, unnatural blazes started by uncaring and negligent humans can do great harm and cause many deaths. What percentage of wildfires do you think are started by humans?',
    answers: {
      a: '10-15%',
      b: '85-90%',
      c: '45-50%',
      d: '25-30%',
    },
    correctAnswer: 'b',
  },
  {
    question: 'If you have lit a campfire before, how did you extinguish it?',
    answers: {
      a: 'I did not extinguish it and waited for it to die on its own',
      b:
        'I extinguished the campfire with a bucket of water and made sure it was fully extinguished.',
      c: 'I have never lit a campfire before.',
      d: 'uhhh',
    },
    correctAnswer: 'b',
  },
  {
    question: 'What are the two most common reasons that forest fires start?',
    answers: {
      a: 'Lightning and human negligence',
      b: 'Spontaneous combustion and erosion',
      c: 'Animals igniting flames and overcrowded bushlands',
      d: 'Strong Wind Patterns',
    },
    correctAnswer: 'a',
  },
  {
    question: 'What time of the year do most forest fires occur?',
    answers: {
      a: 'Summer',
      b: 'Spring',
      c: 'Fall',
      d: 'Winter',
    },
    correctAnswer: 'a',
  },
  {
    question: 'How fast do you think forest fires spread?',
    answers: {
      a: '10.8 km/h',
      b: '6.4 km/h',
      c: '22.2 km/h',
      d: '3.2 km/h',
    },
    correctAnswer: 'a',
  },
  {
    question: 'What do forest fires need in order to burn?',
    answers: {
      a: 'Water',
      b: 'High humidity',
      c: 'Fuel',
      d: 'Clear weather',
    },
    correctAnswer: 'c',
  },
  {
    question:
      'What is one of the main toxic gases present in forest fire smoke?',
    answers: {
      a: 'Osmium tetroxide',
      b: 'Disulfur decafluoride',
      c: 'Tungsten hexafluoride ',
      d: 'carbon monoxide',
    },
    correctAnswer: 'd',
  },
  {
    question:
      'What natural disasters could be caused as a consequence of a destructive forest fire?',
    answers: {
      a: 'Erosion, flash flooding and landslides',
      b: 'Tornadoes',
      c: 'Snow',
      d: 'Tsunami and earthquakes',
    },
    correctAnswer: 'a',
  },
  {
    question: 'What major factor determines a forest fire’s behaviour?',
    answers: {
      a: 'Amount of water vapour in air',
      b: 'Density of Forests',
      c: 'Wind',
      d: 'Hours of sunlight',
    },
    correctAnswer: 'c',
  },
  {
    question: 'What 3 things are needed to start a fire?',
    answers: {
      a: 'Matches, oxygen, wood',
      b: 'Air and sunlight',
      c: 'Fuel, heat, oxygen',
      d: 'Fuel, oxygen, wood',
    },
    correctAnswer: 'c',
  },
  {
    question: 'Which one of these is NOT a type of forest fire?',
    answers: {
      a: 'Crown',
      b: 'Firework',
      c: 'Surface',
      d: 'Ground ',
    },
    correctAnswer: 'b',
  },
  {
    question: 'What was the cause of the Amazon forest fires in 2019?',
    answers: {
      a: 'Deforestation for agriculture usage',
      b: 'Fireworks',
      c: 'Unattended campfire',
      d: 'Arson',
    },
    correctAnswer: 'a',
  },
  {
    question:
      'Which one of these names are NOT an alternate name for forest fires?',
    answers: {
      a: 'Wildfires',
      b: 'Shrub fires',
      c: 'Natural fireworks',
      d: 'Brushfires ',
    },
    correctAnswer: 'c',
  },
  {
    question: 'How many forest fires occurred in 2019?',
    answers: {
      a: '25 653',
      b: '50 477',
      c: '45 809',
      d: '89 431',
    },
    correctAnswer: 'b',
  },
];

function solveSurvey() {
  var x;
  var txt = ' ';
  var i = 0;
  var correct = 0;
  for (i = 0; i < document.forms.length; i  ) {
    x = document.forms[i];
    for (j = 0; j < x.length; j  ) {
      if (x[j].checked) {
        correctAnswer = ourQuestions[i].correctAnswer;
        if (x[j].value == ourQuestions[i].answers[correctAnswer]) {
          correct  = 1;
        }
      }
    }
    document.forms[i].innerHTML  =
      '</div><div class="answer"><input name="q1" value="'  
      ourQuestions[i].answers[j]  
      '" id="value4" type="radio" />'  
      ourQuestions[i].answers[j]  
      '<br/>';
  }
  document.getElementById('questions').innerHTML  =
    'Correct answers: '   correct;
}
  

введите описание изображения здесь

Комментарии:

1. большое вам спасибо, сосос, я действительно, очень, очень ценю это!! @Link

2. также, когда пользователь заполняет анкету, как я могу предоставить им конечный результат?

3. Вам нужно будет реализовать эту функциональность в методе solveSurvey, который является функцией-обработчиком для события нажатия кнопки.

4. Я думал, что уже реализовал это, есть ли что-то, что я делаю неправильно с этим кодом?

5. Если, «предоставляя пользователю его результат», вы имеете в виду отображение его оценки, тогда вам просто нужно отобразить «правильную» переменную в пользовательском интерфейсе. 🙂

Ответ №2:

Я запустил его в jsfiddle и получил следующую ошибку:

«ReferenceError: buttonClicked не определен»

Я полагаю, у вас есть некоторые проблемы с форматированием в вашем коде. Я переместил вашу кнопку вверх по странице, и она начала работать. Проверьте скрипку.

   <body >
  <button class="button" onclick="buttonClicked(this)">Start Questionnaire</button>
  

Я также удалил ваш JavaScript, за исключением buttonClick функции.

Вам нужно добавлять свой код, пока он не заработает.

Вот отредактированная скрипка, которая показывает ваши вопросы:

https://jsfiddle.net/raddevus/jbec837y/10/

Комментарии:

1. ^ забыл пометить u

2. @28space_junkiee Вы можете скопировать код в моей ссылке на вторую скрипку (обновленный ответ), и вы будете в пути. 2-й показывает ваши вопросы.

Ответ №3:

В ourQuestions вы создали ответы в виде объекта, как показано ниже

 answers: {
      a: '10-15%',
      b: '85-90%',
      c: '45-50%',
      d: '25-30%'
}
  

но в коде вы пытаетесь получить его длину

 for (j = 0; j < ourQuestions[i].answers.length; j  )
  

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