javascript - 动态测验 - 支持

标签 javascript jquery html css handlebars.js

我看到了这个quiz code我一直在尝试修改它,以便可以按如下方式运行

点击开始测验 > 问题 > 回答问题> 测验结束

所以基本上用户将通过单击按钮开始测验来开始测验,一旦用户回答了问题,用户将看到每个问题的正确答案;一旦所有问题都得到回答,用户将在测验结束时看到他的结果。

/*jshint strict:false */


$(function() {

  'use strict';


  var questions = [{
    question: 'What is bacon?',
    choices: ['True', 'False'],
    correctAnswer: 0,
    answertext: 'The food of angels'
  }, {
    question: 'Jim didn\'t ate it?',
    choices: ['True', 'False'],
    correctAnswer: 1,
    answertext: 'Oh, He sure did.'
  }, {
    question: 'Did he deserve it?',
    choices: ['True', 'False'],
    correctAnswer: 0,
    answertext: 'NO, no he did not.'
  }, {
    question: 'He will make more?',
    choices: ['True', 'False'],
    correctAnswer: 0,
    answertext: 'He better be cooking.'
  }, {
    question: 'Will he eat it again?',
    choices: ['True', 'False'],
    correctAnswer: 1,
    answertext: 'As tempting as it sounds, No'
  }];

  var questionCounter = 0, //Tracks question number
    selections = [], //Array containing user choices
    quiz = $('.quiz-component'), //Quiz div object
    answer = $('.quiz-component'); //Quiz div object

  // Displays next requested element
  function displayNext() {
    quiz.fadeOut(function() {
      $('#question-area').remove();
      $('#answer-area').remove();

      if (questionCounter < questions.length) {

        var nextQuestion = createQuestionElement(questionCounter),
          answerQuestion = showAsnwerElement(questionCounter);

        //$('#answer-area').remove();
        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();
          //$('#question-area').remove();
          answer.append(answerQuestion).fadeIn();
        } else if (questionCounter === 0) {

          $('#prev').hide();
          $('#next').show();
        }

      } else {
        var scoreElem = displayScore();
        quiz.append(scoreElem).fadeIn();
        $('#next').hide();
        $('#prev').hide();
        $('#start').show();
      }
    });
  }

  // Display initial question
  displayNext();

  // Click handler for the 'next' button
  $('#next').on('click', function(e) {
    e.preventDefault();

    // Suspend click listener during fade animation
    if (quiz.is(':animated')) {
      return false;
    }
    choose();

    // If no user selection, progress is stopped
    if (isNaN(selections[questionCounter])) {
      //$('.qalert').remove();
      $('.question').append('<p class=\'qalert\'>Please make a selection!<p>');
    } else {
      questionCounter++;
      displayNext();
    }
  });

  // 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(e) {
    e.preventDefault();

    if (quiz.is(':animated')) {
      return false;
    }
    questionCounter = 0;
    selections = [];
    displayNext();
    $('#start').hide();
  });

  // Animates buttons on hover
  $('.button').on('mouseenter', function() {
    $(this).addClass('active');
  });

  $('.button').on('mouseleave', function() {
    $(this).removeClass('active');
  });

  // Creates and returns the div that contains the questions and 
  // the answer selections
  function createQuestionElement(index) {
    var qElement = $('<div>', {
      id: 'question-area'
    });

    var header = $('<p class=\'question-number\'>Question ' + (index + 1) + ':</p>');
    qElement.append(header);

    var question = $('<p class=\'question\'>').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>'),
      item,
      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;
  }

  // Creates and returns the div that contains the correct anwser 
  function showAsnwerElement(index) {
    var aElement = $('<div>', {
      id: 'answer-area'
    });

    var header = $('<p class=\'correct-answers\'>').append(questions.correctAnswer).toString();
    aElement.append(header);

    var answer = $('<p class=\'answers\'>').append(questions[index].answertext);
    aElement.append(answer);

    return aElement;
  }

  // Reads the user selection and pushes the value to an array
  function choose() {
    selections[questionCounter] = +$('input[name="answer"]:checked').val();
  }



  // Computes score and returns a paragraph element to be displayed
  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 <span class="correntAns">' + numCorrect + '</span> questions out of <span class="correntAns">' + questions.length + '</span> right!!!');
    return score;
  }
});
.fl-qbgi-slide {
  position: relative;
}
.img {
  visibility: hidden;
}
.fl-quiz-component {
  display: block;
  position: absolute;
  top: 0;
  width: 100%;
}
.title {
  background-color: $brand-primary;
}
p {
  text-align: center;
  padding: 5px 12px;
}
.quiz-section {
  background-color: rgba(0, 66, 131, 0.5);
  color: #FFFFFF;
  font-family: $font-family-sans-serif-condensed;
  font-size: $font-size-large;
  height: auto;
  min-height: 320px;
  position: relative;
}
.quiz-component {
  height: auto;
  margin: auto;
  padding: 20px 15px 10px;
  position: relative;
  width: 85%;
}
.button {
  background-color: $gray-light;
  color: $brand-primary;
  float: right;
  margin: 0 2px 0 2px;
  padding-left: 5px;
  padding-right: 5px;
  position: relative;
}
.button.active {
  background-color: $gray-light;
  color: $brand-primary;
}
button {
  float: right;
  position: relative;
}
.button a {
  color: $brand-primary;
  text-decoration: none;
  padding: 5px 15px;
}
ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}
#prev {
  display: none;
}
#start {
  display: none;
  width: 150px;
}
.correntAns {
  @extend %text-17px-bold-italics-caps;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
--- title: Quiz ---

<div class='fl-qbgi-slide'>
  <div class="img">
    <!--
                {{#if image}}
                    {{#with image}}
                        {{> image}}
                    {{/with}}
                {{else}}
                    {{#parseJSON '{
                        "srcDesktop": "/img-placeholders/botm-bg-grain-0.jpg",
                        "srcTablet": "/img-placeholders/botm-bg-grain-0.jpg",
                        "srcPhone": "/img-placeholders/botm-bg-grain-0.jpg",
                        "altText": "Beer of the Month Carousel Slide"
                    }'}}
                        {{> image}}
                    {{/parseJSON}}
                {{/if}}
  -->
  </div>

  <div class="fl-quiz-component">
    <div class="quiz-section">

      <div class="title">
        <p>Seafood Sustainability Quiz</p>
      </div>

      <div class='quiz-component'></div>

      <!-- handlebars temp area
                #quiz-questions}}
                <div class="question-block">
                    <p class="">{{{default quiz-question}}}</p>
                    <a class="">True</a>
                    <a class="">false</a>
                </div>
                /quiz-question}}
                -->

      <div class='button' id='next'><a href='#'>Next</a>
      </div>
      <div class='button' id='prev'><a href='#'>Prev</a>
      </div>
      <div class='button' id='start'> <a href='#'>Start Over</a>
      </div>
      <!-- 
                <button class='' id='next'>Next</a></button>
                <button class='' id='prev'>Prev</a></button>
                <button class='' id='start'> Start Over</a></button>
                -->

    </div>

  </div>
</div>

<script src="/js/apps/quiz-component/main.js"></script>

我在哪里需要帮助

  1. 需要能够在用户提交答案后和显示下一个问题之前显示每个问题的正确答案。

我已经调整了一个代码来显示答案,但在同一屏幕上显示下一个问题。需要它只显示答案,用户将单击下一步,然后将显示下一个问题。

  1. 需要展示两张不同的背景图片;一个在问题期间,另一个在测验结束时。

不需要,但肯定有帮助

  1. 如果我能看到这段用 Handlebars.js 编写的代码,那将非常有帮助,因为我正在尝试学习 Handlebars

最佳答案

好的,我将用 javascript 回答这个问题(我对 handlebars.js 了解不多)。

要在每次用户提交后显示答案,请将点击事件附加到单选按钮。我注意到您正在使用 jquery。

   $("#trueRadioBut").on("click",function(){
        //check your answer
        if(right)
           display answerText;
           update score ...etc... 
        else
           wrong option code.   

   });

对错误的单选按钮也做同样的事情。如果用户是正确的,这应该显示 answerText。

背景的改变也可以使用 jquery 和一个额外的 CSS 类来完成。在你的 css 中有一个类,也许是一个具有不同背景的 .endBackground。然后您可以使用 jquery 的 toggleClass() 切换它。 toggleClass() 为元素交替打开和关闭类。

为此,您还需要更改 next 按钮。向其添加一个点击事件,获取下一个问题并重定向到下一页。当没有更多问题时,切换背景。

$(body).toggleClass("endBackground");

这应该会改变您的背景。要在重新启动时改回正常背景,请向您的 startover 按钮添加一个点击事件,以再次关闭该类。

希望我已经说清楚了。有疑问可以问我。

关于javascript - 动态测验 - 支持,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37647891/

相关文章:

html - 当我们关注链接时如何为 child 添加样式 block ?

javascript - 通过文件输入从视频文件创建缩略图

javascript - jQuery Datatables 过滤器外部表包装的问题

javascript - 如何使用 JavaScript 或 JQuery 在页面加载时更改 Div 元素的样式宽度?

jquery - 在多个 ul 和返回值中计算 li

javascript - 为什么 href ="#"的优先级高于 onclick

javascript - Jquery - 嵌套列表的自动递增 ID

javascript - 如何在 d3.js 中移动圆圈(数据点)

javascript - 使用 Javascript 转义 HTML5 数据属性中的引号

javascript - 未捕获的语法错误 : Unexpected reserved word on older android version