添加随机问题的答案测验javascript

时间:2017-05-10 13:17:56

标签: javascript

我目前正在使用Javascript进行测验,随机化问题和答案。我有随机问题,但如何添加答案以及某个问题呢?我还希望每个答案都放在自己的div中,如下所示:http://imgur.com/a/l9w9j

这是我到目前为止的代码:

var display = document.getElementById("questions");
var questions = ['What is the weather like?',
                'What time of day is it?',
                'Whats your favourite music?',
                'Which season is your favourite?',
                'What colour are your eyes?'];

var questionTracker = [];
var questionAmount = 1;

// Iterate however many times
for (var i = 0; i < questionAmount; i++) {
  // Keep creating random numbers until the number is unique
  do {
    var randomQuestion = Math.floor(Math.random() * questions.length);
  } while (existingQuestions());

  display.innerHTML += questions[randomQuestion] + '<br>';
  // Add the question to the tracker
  questionTracker.push(randomQuestion);
}

// If the current random number already exists in the tracker, return true
function existingQuestions() {
  for (var i = 0; i < questionTracker.length; i++) {
    if (questionTracker[i] === randomQuestion) {
      return true;
    }
  }
  return false;
}

我的HTML:

<div id="questions">
</div>

<div id="answers">
<div class="answers-left">
        <div class="answer1" tabIndex="1">Sunny</div>
        <div class="answer2" tabIndex="2">Raining</div>
    </div>
    <div class="answers-right">
        <div class="answer3" tabIndex="3">Cloudy</div>
        <div class="answer4" tabIndex="4">Windy</div>
    </div>

        <div class="clear"></div>
    </div>

4 个答案:

答案 0 :(得分:0)

她可以使用object而不是array

var questionData=    {
        "questions":[
           {
          "question":"this is hard question to answer",
          "answers":[
                    "yes","no","why not","none"
                   ]
            },
            {
            "question":"this is 2nd hard question to answer",
            "answers":[
                    "yes","no","why not","none"
                    ]
            }
           ]
    }

questionData.map(function(question){
    //Here you can write the dom structure that you like
})

答案 1 :(得分:0)

您可以将您的问题和答案存储在一组对象中

每个对象都包含questionanswers属性。 answers是一个包含每个可能答案的数组。

以下代码将使用Math.random()随机搜索一个随机索引。使用此索引,您可以选择数组中的对象,然后选择问题和答案。

我添加了一些CSS来添加所需的效果。这可以通过颜色/尺寸/边距/ ...你想要

来改善

var questionElement = document.getElementById("questions");
var answersElements = document.getElementsByClassName("answer");
var data = [{
  question: 'What is the weather like?',
  answers: ['Sunny', 'Raining', 'Cloudy', 'Windy']
}, {
  question: 'What time of day is it?',
  answers: ['Morning', 'Lunch', 'Evening', 'Night']
}];

var randomIndex = Math.floor(Math.random() * data.length);

questionElement.innerHTML = data[randomIndex].question;

for (let i = 0; i < answersElements.length; i++) {
  answersElements[i].innerHTML = data[randomIndex].answers[i];
}
.answer {
  display: inline-block;
  background-color: #00BCD4;
  margin: 1em;
}
<div id="questions">
</div>

<div id="answers">
  <div class="answers-left">
    <div class="answer" tabIndex="1">Sunny</div>
    <div class="answer" tabIndex="2">Raining</div>
  </div>
  <div class="answers-right">
    <div class="answer" tabIndex="3">Cloudy</div>
    <div class="answer" tabIndex="4">Windy</div>
  </div>

  <div class="clear"></div>
</div>

答案 2 :(得分:0)

为什么不在对象数组中添加问题的答案?

&#13;
&#13;
var display = document.getElementById("questions");
var answers = document.getElementById("answers");
var answersLeft = document.getElementById("answers-left");
var answersRight = document.getElementById("answers-right");

var questions = [{
    "q": "What is the weather like?",
    "a": [
      "Sunny",
      "Raining",
      "Cloudy",
      "Windy"
    ]
  },
  {
    "q": "What time of day is it?",
    "a": [
      "Sunny",
      "Raining",
      "Cloudy",
      "Windy"
    ]
  },
  {
    "q": "Whats your favourite music?",
    "a": [
      "Sunny",
      "Raining",
      "Cloudy",
      "Windy"
    ]
  },
  {
    "q": "Which season is your favourite?",
    "a": [
      "Sunny",
      "Raining",
      "Cloudy",
      "Windy"
    ]
  },
  {
    "q": "What colour are your eyes?",
    "a": [
      "Sunny",
      "Raining",
      "Cloudy",
      "Windy"
    ]
  }
];

var questionTracker = [];
var questionAmount = 1;

// Iterate however many times
for (var i = 0; i < questionAmount; i++) {
  // Keep creating random numbers until the number is unique
  do {
    var randomQuestion = Math.floor(Math.random() * questions.length);
  } while (existingQuestions());

  display.innerHTML += questions[randomQuestion].q + '<br>';
  var answersToQ = questions[randomQuestion].a;

  for (var j = 0; j < answersToQ.length; j++) {
    var answer = "<p>" + answersToQ[j] + "</p>";
    if (j % 2 === 0) {
      answersLeft.innerHTML += answer;
    } else {
      answersRight.innerHTML += answer;
    }
  }

  // Add the question to the tracker
  questionTracker.push(randomQuestion);
}

// If the current random number already exists in the tracker, return true
function existingQuestions() {
  for (var i = 0; i < questionTracker.length; i++) {
    if (questionTracker[i] === randomQuestion) {
      return true;
    }
  }
  return false;
}
&#13;
<style type="text/css">
  #answers-left {
    position: relative;
    float: left;
    width: 50%;
  }
  
  #answers-right {
    position: relative;
    float: right;
    width: 50%;
  }
  
  #answers p {
    background-color: blue;
    width: 50%;
    text-align: center;
    color: #fff;
    cursor: pointer;
  }
</style>

<div id="questions">
</div>

<div id="answers">
  <div id="answers-left">
  </div>
  <div id="answers-right">
  </div>
</div>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

这是我用以下代码为您制作的示例。 抱歉,但我没有时间制定ccs规则,但你可以看到问题是混合的,所有问题的答案都是混合的。 http://devel.vis25.com/test.php

我建议你使用这样的东西,对于我的例子,你需要Jquery和Jquery模板

这是Jquery下载jquery tempaltes

的链接

以下是你的tempaltes和html的例子。

<html>
<head>
<script src="https://devel.vis25.com//Vendors/JqueryUI/external/jquery/jquery.js"></script>
<script src="http://devel.vis25.com/Vendors/jquery.tmpl.min.js"></script>
</head>
<body onload="RenderQuestions();">
    <div id="Questions"></div>
    <script id="Question-Tempalte" type="text/x-jQuery-tmpl">
         <div class="Question" id=question-"${ID}">
              <div class="Question-text">${QuestionText}</div>
              <div class="Question-answer-container" id="Question-answer-container-${ID}"></div>
         </div>
    </script>

    <script id="Answer-Tempalte" type="text/x-jQuery-tmpl">
         <div class="answer" id="answer-${ID}">
              <div class="answer-text" tabIndex="${ID}">${answerText}</div>
         </div>
    </script>
</body>
</html>

用javascript做这样的事情。

//Function that is called in body 'onload' event.
function RenderQuestions(){
    //Array of you'r questions as json objects 
    var questions = [
        { ID : '1', QuestionText : 'What is the weather like?' },
        { ID : '2', QuestionText : 'What time of day is it?' },
        { ID : '3', QuestionText : 'Whats your favourite music?' },
        { ID : '4', QuestionText : 'Which season is your favourite?' },
        { ID : '5', QuestionText : 'What colour are your eyes?' },
    ];
    //Call shuffle function for your questions, so they are mixed randomly.
    var ShuffledQuestions = shuffle( questions );

    //Loop true all of your questions and render them inside of your questions <div>
    //Allso call functions 'RenderAnswers()' by question id value[ 'ID' ].
    $.each(ShuffledQuestions, function(index, value){
        $( '#Question-Tempalte' ).tmpl( value ).appendTo( '#Questions' );
        RenderAnswers( value[ 'ID' ] );
    });
}

//Shuffle function return randomly mixed array.
function shuffle( array ) {
    var currentIndex = array.length, temporaryValue, randomIndex;
    while (0 !== currentIndex) {

    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

//RenderAnswers function takes QuestionID as argument so we can render answer elements for right questions, and we have right answers.
function RenderAnswers( QuestionID ){
    var Answers = [];

    //Check which question are we rendering.

    //Answers for question ID 1 ( 'What is the weather like?' ).
    if( QuestionID == 1){
        Answers = [
            { AnswersID : 1 , answerText : 'Sunny' },
            { AnswersID : 2 , answerText : 'Raining'},
            { AnswersID : 3 , answerText : 'Cloudy'},
            { AnswersID : 4 , answerText : 'Windy'},                
        ];
    }

    //Answers for question ID 2 ( 'What time of day is it?' ).
    if( QuestionID == 2){
        Answers = [
            { AnswersID : 1 , answerText : '8:00' },
            { AnswersID : 2 , answerText : '12:00'},
            { AnswersID : 3 , answerText : '18:00'},
            { AnswersID : 4 , answerText : '00:00'},                    
        ];
    }

    //Answers for question ID 3 ( 'Whats your favourite music?' ).
    if( QuestionID == 3){
         Answers = [
            { AnswersID : 1 , answerText : 'Rock' },
            { AnswersID : 2 , answerText : 'pop'},
            { AnswersID : 3 , answerText : 'rap'},
            { AnswersID : 4 , answerText : 'EDM'},                  
        ];
    }

    //Answers for question ID 4 ( 'Which season is your favourite?' ).
    if( QuestionID == 4){
        Answers = [
            { AnswersID : 1 , answerText : 'Summer' },
            { AnswersID : 2 , answerText : 'Winter'},
            { AnswersID : 3 , answerText : ''},
            { AnswersID : 4 , answerText : ''},                 
        ];
    }

        //Answers for question ID 5 ( 'What colour are your eyes?' ).
    if( QuestionID == 4){
        Answers = [
            { AnswersID : 1 , answerText : 'blue' },
            { AnswersID : 2 , answerText : 'brown'},
            { AnswersID : 3 , answerText : 'green'},
            { AnswersID : 4 , answerText : ''},                 
        ];
    }

    //Shuffle answers.
    var ShuffledAnswers = shuffle( Answers );

    //Renders answer elements for question.
    $( '#Answer-Tempalte' ).tmpl( ShuffledAnswers ).appendTo( '#Question-answer-container-'+QuestionID );
}

希望我能够帮助你,随时可以提出任何问题我是不理解你的问题吧!

祝你好运, Vis25