使用javascript显示测验问题

时间:2016-11-13 00:37:58

标签: javascript json

我目前正在做javascriptissexy.com学习路径。我无法找出显示测验问题的最佳方法。我的问题是作为初学javascript学生。我该如何解决开发测验应用程序行为的方法。如果你查看我的代码,我已将我的问题存储在JSON中。那么如何向用户显示问题,以便他或她能够回答问题并与程序进行交互?

var questions = [{

  questions: "What is the name of the biggest part of the human brain?",
  choices : ["cerebrum", "Thalamus","Medulla", "Cerebellum"],
  correstAnswer: 0
},
{
  questions: "The colored part of the human eye that controls how much light passes through the pupil is called the?",
  choices: ["Pupil", "Rods", "Iris", "Cornea"],
  correctAnswer: 2
},
{
  questions: "What is the name of the substance that gives skin and hair its pigment?",
  choices: ["Dermis", "Melanin", "Swear Gland", "Epiderms"],
  correctAnswer: 1
},
 { 
  questions: "The muscles found in the front of your thighs are known as what?",
  choices: ["Adductor", "petella", "tibia", "Quadriceps"],
   correctAnswer: 3
 },
 {
   questions: "15. The shape of DNA is known as?",
   choices: ["Double helix", "Adenine helix", "tri helix", "thymine"],
   correctAnswer: 0
 }, 
 {
   questions: "A structure composed of two or more tissues is termed?",
   choices: ["serous membrane", "complex tissue", "organ system", "organ"],
   correctAnswer: 3
 },
 {
   questions: "The heart is ____ to the lungs?",
   choices: ["superior", "dorsal", "medial", "lateral"],
   correctAnswer: 2
 }, 
  {
    questions: "Male hormones are produced by which of the following?",
    choices: ["prostate", "testes", "vas deferens", "prepuce"],
    correctAnswer: 1
  },
   {
     questions: "Which of the following terms describes the body's ability to maintain its normal state?",
     choices: ["anabolism", "catabolism", "tolerance", "homoestasis"],
     correctAnswer: 3
   }, 
    {
      questions: "Each of the following is known to help prevent infection EXCEPT?",
      choices: ["hair in nose", "mucous membranes", "osteoblasts", "saliva"],
      correctAnswer: 3
    }  ];
/*
 * Question variables
 */
var currentQuestions = 0;
var currentAnswer = 0;
var quizDone = false;


$(document).ready(function(){

/* 
 * Show current question
 */
  displayQuestions();

  function randomize(questions) {
    var currentIndex = questions.length; 
    var tempQuestion, randomIndex;

    //pick remaining element
    while (currentIndex > 1 ) {
      randomIndex = math.floor(math.random() * currentIndex);
     currentIndex -= 1;
     tempQuestion = question[currentIndex];
      questions[currentIndex] = questions[randomIndex];
      questions[randomIndex] = tempQuestion;

    }
    return questions;
  }


});

我的codepen链接是https://codepen.io/OA11an/pen/jVWMEy?editors=0010

3 个答案:

答案 0 :(得分:4)

这是解决方案。希望它有所帮助!



var questions = [{
  
  question: "What is the name of the biggest part of the human brain?",
  choices : ["cerebrum", "Thalamus","Medulla", "Cerebellum"],
  correstAnswer: 0
},
{
  question: "The colored part of the human eye that controls how much light passes through the pupil is called the?",
  choices: ["Pupil", "Rods", "Iris", "Cornea"],
  correctAnswer: 2
},
{
  question: "What is the name of the substance that gives skin and hair its pigment?",
  choices: ["Dermis", "Melanin", "Swear Gland", "Epiderms"],
  correctAnswer: 1
},
 { 
  question: "The muscles found in the front of your thighs are known as what?",
  choices: ["Adductor", "petella", "tibia", "Quadriceps"],
   correctAnswer: 3
 },
 {
   question: "15. The shape of DNA is known as?",
   choices: ["Double helix", "Adenine helix", "tri helix", "thymine"],
   correctAnswer: 0
 }, 
 {
   question: "A structure composed of two or more tissues is termed?",
   choices: ["serous membrane", "complex tissue", "organ system", "organ"],
   correctAnswer: 3
 },
 {
   question: "The heart is ____ to the lungs?",
   choices: ["superior", "dorsal", "medial", "lateral"],
   correctAnswer: 2
 }, 
  {
    question: "Male hormones are produced by which of the following?",
    choices: ["prostate", "testes", "vas deferens", "prepuce"],
    correctAnswer: 1
  },
   {
     question: "Which of the following terms describes the body's ability to maintain its normal state?",
     choices: ["anabolism", "catabolism", "tolerance", "homoestasis"],
     correctAnswer: 3
   }, 
    {
      question: "Each of the following is known to help prevent infection EXCEPT?",
      choices: ["hair in nose", "mucous membranes", "osteoblasts", "saliva"],
      correctAnswer: 3
    }  ];

$(document).ready(function(){
  
  var questionCounter = 0; //Tracks question number
  var selections = []; //Array containing user choices
  var quiz = $('#quiz'); //Quiz div object
  
  // Display initial question
  displayNext();
  
  // Click handler for the 'next' button
  $('#next').on('click', function () {
    
    // Suspend click listener during fade animation
    if(quiz.is(':animated')) {        
      return false;
    }
    choose();
    
    // If no user selection, progress is stopped
    if (isNaN(selections[questionCounter])) {
      alert('Please make a selection!');
    } else {
      questionCounter++;
      displayNext();
    }
    return false;
  });
  
  // Click handler for the 'prev' button
  $('#prev').on('click', function (e) {
    e.preventDefault();
    
    if(quiz.is(':animated')) {
      return false;
    }
    choose();
    questionCounter--;
    displayNext();
  });
  
  // Click handler for the 'Start Over' button
  $('#start').on('click', function () {
    if(quiz.is(':animated')) {
      return false;
    }
    questionCounter = 0;
    selections = [];
    displayNext();
    $('#start').hide();
    return false;
  });
  
  // Creates and returns the div that contains the questions and 
  // the answer selections
  function createQuestionElement(index) {
    var qElement = $('<div>', {
      id: 'question'
    });
    
    var header = $('<h3>Question ' + (index + 1) + ':</h3>');
    qElement.append(header);
    
    var question = $('<p>').append(questions[index].question);
    qElement.append(question);
    
    var radioButtons = createRadios(index);
    qElement.append(radioButtons);
    
    return qElement;
  }
  
  // Creates a list of the answer choices as radio inputs
  function createRadios(index) {
    var radioList = $('<ul>');
    var item;
    var input = '';
    for (var i = 0; i < questions[index].choices.length; i++) {
      item = $('<li>');
      input = '<input type="radio" name="answer" value=' + i + ' />';
      input += questions[index].choices[i];
      item.append(input);
      radioList.append(item);
    }
    return radioList;
  }
  
  // Reads the user selection and pushes the value to an array
  function choose() {
    selections[questionCounter] = +$('input[name="answer"]:checked').val();
  }
  
  // Displays next requested element
  function displayNext() {
    quiz.fadeOut(function() {
      $('#question').remove();
      
      if(questionCounter < questions.length){
        var nextQuestion = createQuestionElement(questionCounter);
        quiz.append(nextQuestion).fadeIn();
        if (!(isNaN(selections[questionCounter]))) {
          $('input[value='+selections[questionCounter]+']').prop('checked', true);
        }
        
        // Controls display of 'prev' button
        if(questionCounter === 1){
          $('#prev').show();
        } else if(questionCounter === 0){
          
          $('#prev').hide();
          $('#next').show();
        }
      }else {
        var scoreElem = displayScore();
        quiz.append(scoreElem).fadeIn();
        $('#next').hide();
        $('#prev').hide();
        $('#start').show();
      }
    });
  }
  
  function displayScore() {
    var score = $('<p>',{id: 'question'});
    
    var numCorrect = 0;
    for (var i = 0; i < selections.length; i++) {
      if (selections[i] === questions[i].correctAnswer) {
        numCorrect++;
      }
    }
    
    score.append('You got ' + numCorrect + ' questions out of ' +
                 questions.length + ' right!');
    return score;
  }
  
});
&#13;
body {
  background-image: url(http://7te.org/images/570x363/anatomyhuman-anatomy-human-1280x800-wallpaper-body-wallpaper-76530.jpg);
}
a{
  text-decoration: none;
}

h1 {
  text-align: center;
  font-size: 45px;
  font-family: cursive;
  color: teal;
 text-shadow: 2px 1px black;

  
}
ul {
 margin-right: auto;
 margin-left: auto;
}

li {
 list-style: none;
}

.radiochoices{
  font-family: comic sans ms;
  color: white;
  font-size: 20px;
} 

#container {
    margin:auto;
    width: 50%;
    padding: 0px 0px 30px 0px;
    background-color: #1E90FF;
    border:4px solid #B0E0E6;
    border-radius: 13px;
    color: #FFFFFF;
    font-weight: bold;
    box-shadow: 5px 5px 10px #888;
}

.center {
  margin: 205px 40px 0px 245px
}
.reset {
  display:none;
}
&#13;
<script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div id='container'>
      <div id='title'>
        <h1 class="title"> Human Anatomy Questions </h1>
      </div>
        <br/>
        <div id='quiz'></div>
        <button class="btn btn-info btn-large" id='next'><a href='#'>Next</a></button>
        <button class="btn btn-warning btn-large reset" id='prev'><a href='#'>Prev</a></button>
        <button class="btn btn-info btn-large" id='start'> <a href='#'>Start Over</a></button>
      </div>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

我在HenryDev的回答之前开始写这篇文章,即使我看到他已经完成并且答案被接受了,我认为无论,这都是很好的阅读信息。

这是许多人使用和使用的基本编码理念,并且有一些不同的版本。它简称为模型 - 视图 - 控制器(MVC)。它试图帮助您将代码分成不同的块,这样您就不会被许多人称为&#34; Spaghetti代码&#34; (代码只是...到处都是。)

这方面的基础知识,并且在你的干草叉出现之前请所有人参加这些我对MVC的理解,因为我多年来一直在捡起它,所以如果它不是逐字的那么会说,不要让我这样做,如下:

模型

模型的全部意义在于简单而单独地负责获取数据。您使用的数据是否是测验问题/答案,页面上生成的随机数,航空公司信息等等。代码模型是存储的位置。

代码中的每个类型模型应该具有不同的模型对象/类(取决于您使用的语言)。所以在这种情况下你有一个Questions模型,也就是你所有问题的汇总集合,我会说的是Question(注意,没有&#39; s,#sing; )。 Questions作业是从您存储它们的任何地方提取正确的Question对象。该方法将根据您使用的系统组成而变化(MEAN堆栈,LAMP堆栈,您可以使用的千种不同适用堆栈的插入列表)。 Question工作只是存储一个问题的相关数据(问题,答案选择,正确答案等)。

视图

该视图负责从您的模型中获取数据并执行两项操作

  1. 以合乎逻辑的方式显示它。根据具体情况,重大会有所不同。我遵循的基本想法是,我不会以与显示导航菜单相同的方式显示博客文章。这完全取决于你所展示的内容。在开始观察之前,我最大的建议是考虑对此有何意义。
  2. 将其与控制器中的操作相关联,以修改或更改数据。
  3. 控制器

    控制器在所有这些中都是大老板,即使它经常列在最后。您的控制器是所有工作背后的逻辑机器,因为模型的工作只是获取数据,而查看的主要工作是显示数据,控制器是大多数应用程序逻辑应该去的地方。它决定应该使用哪些模型,并且通常 a (可以有多个)控制器决定应该显示什么 View

    考虑到所有这些,这是我刚刚做的基本设置。 (很简单,我使用jQuery和Bootstrap来帮助我以最小的努力使它漂亮)。

    &#13;
    &#13;
    $(function() {
        //This notation for jQuery calls a function when the Dom is ready or page has loaded. I can never remember. I use it as a short hand for $(document).ready but I could be totally wrong.
    
        //Because I read that you are a beginner in javascript, let's just assume that our Questions array a very basic Model.
        //And that each object in the array is a Question model. Once you get some more practice, this should make a lot more sense.
        var Questions = [{
    
          questions: "What is the name of the biggest part of the human brain?",
          choices: ["Cerebrum", "Thalamus", "Medulla", "Cerebellum"],
          correctAnswer: 0
        }, {
          questions: "The colored part of the human eye that controls how much light passes through the pupil is called the?",
          choices: ["Pupil", "Rods", "Iris", "Cornea"],
          correctAnswer: 2
        }, {
          questions: "What is the name of the substance that gives skin and hair its pigment?",
          choices: ["Dermis", "Melanin", "Swear Gland", "Epiderms"],
          correctAnswer: 1
        }, {
          questions: "The muscles found in the front of your thighs are known as what?",
          choices: ["Adductor", "petella", "tibia", "Quadriceps"],
          correctAnswer: 3
        }, {
          questions: "The shape of DNA is known as?",
          choices: ["Double helix", "Adenine helix", "tri helix", "thymine"],
          correctAnswer: 0
        }, {
          questions: "A structure composed of two or more tissues is termed?",
          choices: ["serous membrane", "complex tissue", "organ system", "organ"],
          correctAnswer: 3
        }, {
          questions: "The heart is ____ to the lungs?",
          choices: ["superior", "dorsal", "medial", "lateral"],
          correctAnswer: 2
        }, {
          questions: "Male hormones are produced by which of the following?",
          choices: ["prostate", "testes", "vas deferens", "prepuce"],
          correctAnswer: 1
        }, {
          questions: "Which of the following terms describes the body's ability to maintain its normal state?",
          choices: ["anabolism", "catabolism", "tolerance", "homoestasis"],
          correctAnswer: 3
        }, {
          questions: "Each of the following is known to help prevent infection EXCEPT?",
          choices: ["hair in nose", "mucous membranes", "osteoblasts", "saliva"],
          correctAnswer: 3
        }]; // end Questions
    
        //Many people would now use something called Angular, it's a Javascript library which sort of... links together the view/model sections very nicely. Since you are learning, I will leave that out and do it via straight jQuery.
    
        var question_container = $('#questions-container');
        //Grabs the question container, aka our form.
    
        question_container.on('submit', function(e) {
          e.preventDefault();
          //Let's just stop the default event.
          var questions = $(this).children('.question');
          //This gets each question
          questions.each(function(i, el) {
            var $el = $(el);
            //I do this as a short hand. by default the element passed down is a simply HTML object, and not a jQuery object. I use this notation to keep from getting myself confused
            var selected = $el.find(':checked');
            //This looks through our HTML to find a child element of the Question element we have that is selected;
            $el.toggleClass('bg-danger', selected.val() != $el.data('answer'));
            //This toggles a class I borrowed from bootstrap, bg-danger, if the value is not equal to our answer
            $el.toggleClass('bg-success', selected.val() == $el.data('answer'));
            //This toggles a success class, bg-success, if the value IS equal to the answer we have stored
          });
    
        })
    
        $.each(Questions, function(i, Question) {
          var container = $('<div class="question">'); //Creates a new div with a class of 'question'
          var qHeader = $('<h3>').html(Question.questions); // Creates, and then assigns HTML to , an H3 element that will be the header of our question
          var ul = $('<ul class="list-unstyled">'); //Creates a new list where the answers will be set down, with a class of 'list-unstyled'
    
          container.data('answer', Question.correctAnswer);
          //This is a jQuery thing that stores the correct answer on the container (div.question) so that we don't have to loop through questions after questions.
    
          question_container.append(container.append(qHeader));
          //Appends our current container to the form we have up above
    
          $.each(Question.choices, function(j, Choice) {
            //jQuery function, loops through all the choices in the current question. Notice I used j here instead of I to avoid confusion with the $.each call above
            var item = $('<li> ' + Choice + '</li>'); //Creates a new list item with the text for the answer already inserted
            var radio = $('<input type="radio" name="question[' + i + ']" value="' + j + '" />');
            //Creates a radio button, with a very specific name and value. Check the outcome of the HTML and feel free to fiddle with it if you don't understand why i did what I did here.
            radio.prependTo(item);
            //Prepends the radio element to the li so it appears before the Choice text
            item.appendTo(ul);
            //Adds this li item to our list, created above.
          }); // end $.each(Question.choices);
          ul.appendTo(container);
          //Adds the ul to our container
    
        }); //end $.each(Questions);
    
      }) //end $()
    &#13;
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <h1>Let's take a Quiz!</h1>
    <div class="questions container">
      <form action="your_page_here.php" id="questions-container">
        <input type="submit" class="btn btn-success" />
        <input type="reset" class="btn btn-info" />
      </form>
    </div>
    &#13;
    &#13;
    &#13;

    修改

    这是我开发的codepen的链接,因为在某些浏览器上代码片段编辑器的沙盒代码似乎无法正常工作。

    Codepen Here

答案 2 :(得分:1)

我也玩得很开心,让它变得有用。谢谢你的动力。这是我做的:

  • 我在其中一个问题中纠正了错误correstAnswer
  • 我将字段名称questions更正为question
  • 我添加了.correct.wrong CSS类。
  • 我完全重写了JavaScript代码,尽可能保持简单。

https://codepen.io/anon/pen/eBZEEe?editors=1111

剩下要做的事情:

  • 将答案洗牌,让quizzers真正了解答案,而不是他们的位置。