创建条件if / else语句以显示最终测验分数结果

时间:2019-01-19 20:35:52

标签: javascript jquery

不太熟悉Java。但是,我试图使用javascript创建在线测验,其中使用条件if / else语句将测验结果显示为百分比。如果考试分数为70%或更高,请单击此处。否则,如果测试分数低于70%,请单击此处重复测试。到目前为止,这是我迄今为止没有的结果:

var quiztitle = "Quiz";


 var quiz = [
        {
            "question" : "Q1: What colour is the sky?",
            "choices" : [
                                    "Blue",
                                    "Red",
                                    "Pink",
                                    "Green"
                                ],
            "correct" : "Blue",
            
        },
        {
            "question" : "Q2: What colour is mustard?",
            "choices" : [
                                    "Blue",
                                    "Yellow",
                                    "Green",
                                    "Red"
                                ],
            "correct" : "Yellow",
        },
        {
            "question" : "Q3: What colour is grass?",
            "choices" : [
                                    "Blue",
                                    "Yellow",
                                    "Red",
                                    "Green"
                                ],
            "correct" : "Green",
        },
     

    ];


 var currentquestion = 0,
     score = 0,
     submt = true,
     picked;

 jQuery(document).ready(function ($) {


     function htmlEncode(value) {
         return $(document.createElement('div')).text(value).html();
     }


     function addChoices(choices) {
         if (typeof choices !== "undefined" && $.type(choices) == "array") {
             $('#choice-block').empty();
             for (var i = 0; i < choices.length; i++) {
                 $(document.createElement('li')).addClass('choice choice-box').attr('data-index', i).text(choices[i]).appendTo('#choice-block');
             }
         }
     }

      function nextQuestion() {
         submt = true;
         $('#submitbutton').css('display','none');
		 $('#form1').css('display','none');
         $('#explanation').empty();
         $('#question').text(quiz[currentquestion]['question']);
         $('#pager').text('Question ' + Number(currentquestion + 1) + ' of ' + quiz.length);
         addChoices(quiz[currentquestion]['choices']);
         setupButtons();


     }


     function processQuestion(choice) {
         if (quiz[currentquestion]['choices'][choice] == quiz[currentquestion]['correct']) {
             $('.choice').fadeIn(700, function() {
				 $('.choice').eq(choice).css({
                 'background-color': '#6C0',
				 'color': '#ffffff',
				 'font-weight': '300',
  				 'font-size': '20px',
				 'padding' : '20px'
             });
			 });
             $('#explanation').fadeIn(700, function() {
				  $('#explanation').html('<div class="correct"><i class="fal fa-check" style="font-family:FontAwesome; padding:30px 10px 30px 0;"></i> Correct!</div> ' + htmlEncode(quiz[currentquestion]['explanation']));
				  });
             score++;
         } else {
             $('.choice').eq(choice).css({
                 'background-color': '#ff0000',
				 'color': '#ffffff',
				 'font-weight': '300',
  				 'font-size': '20px',
				 'padding' : '20px'
             });
             $('#explanation').fadeIn(700, function() {
				 $('#explanation').html('<div class="wrong"><i class="fal fa-times" style="font-family:FontAwesome; padding:30px 10px 30px 0;"></i> Incorrect.</div> ' + htmlEncode(quiz[currentquestion]['explanation']));
			 });
         }
         currentquestion++;
         $('#submitbutton').fadeIn(700, function() {
			 $('#submitbutton').html('NEXT QUESTION').on('click', function () {
             if (currentquestion == quiz.length) {
                 endQuiz();
             } else {
                 $(this).text('NEXT QUESTION').css({
                 
                 }).off('click');
                 nextQuestion();
             }
         });
         $('#submitbutton').show();
		 });
     }


     function setupButtons() {
         $('.choice').fadeIn(700, function() {
			 $('.choice').on('mouseover', function () {
             $(this).css({
                 'background-color': '#f1cb00',
				 'color': '#005596',
				 'font-weight': '300',
  				 'font-size': '20px',
				 'padding' : '20px'
             });
			 });
         });
         $('.choice').fadeIn(700, function() {
			 $('.choice').on('mouseout', function () {
             $(this).css({
                 'background-color': '#e1e1e1',
				 'color': '#005596',
				 'font-weight': '300',
  				 'font-size': '20px',
				 'padding' : '20px'
              });
			  });
         })
         $('.choice').fadeIn(700, function() {
			 $('.choice').on('click', function () {
             if (submt) {
                 submt = false;
                 picked = $(this).attr('data-index');
                 $('.choice').removeAttr('style').off('mouseout mouseover');
                 $(this).css({
                 
                 });
                 $('.choice').css({
                     'cursor': 'default'
                 });
                 
                 processQuestion(picked);
                 $('#submitbutton').css({
				 'padding' : '20px'
                 });
				 
             }
			  });
         })
     }


     function endQuiz() {
         $('#explanation').empty();
         $('#question').empty();
		 $('.pager').hide();
         $('#choice-block').empty();
         $('#submitbutton').remove();
         $(document.createElement('h2')).css({
			 'line-height' : '20px',
			 'text-align' : 'center'
         }).text(Math.round(score / quiz.length * 100) + '%').insertAfter('#question');
		 
		 
		 $('#form1').show();
     }
	 



     function init() {
         //add title
         if (typeof quiztitle !== "undefined" && $.type(quiztitle) === "string") {
             $(document.createElement('header')).text(quiztitle).appendTo('#frame');
         } else {
             $(document.createElement('header')).text("Quiz").appendTo('#frame');
         }

         //add pager and questions
         if (typeof quiz !== "undefined" && $.type(quiz) === "array") {
             //add pager
             $(document.createElement('p')).addClass('pager').attr('id', 'pager').text('Question 1 of ' + quiz.length).appendTo('#frame');
             //add first question
             $(document.createElement('h2')).addClass('question').attr('id', 'question').text(quiz[0]['question']).appendTo('#frame');
             
             $(document.createElement('p')).addClass('explanation').attr('id', 'explanation').html('&nbsp;').appendTo('#frame');

             //questions holder
             $(document.createElement('ul')).attr('id', 'choice-block').appendTo('#frame').css({
				'padding-top' : '20px'
              })//add choices
             addChoices(quiz[0]['choices']);
             
             //add submit button
             $(document.createElement('div')).addClass('choice-box').attr('id', 'submitbutton').text('NEXT QUESTION').css({
                 
             }).appendTo('#frame');

             setupButtons();
             $('#submitbutton').hide();
			 $('#form1').hide();
         }
     }

     init();
 });
 
 
 
 
  header {
	background: #005596;
	color:#ffffff;
	padding:20px;
	overflow:auto;
	font-size:21pt;
	margin-bottom:40px;
	-webkit-border-radius: 5px;
      -moz-border-radius: 5px;
      border-radius: 5px;
	}
 
.correct {
	color:#6C0; font-family:Tahoma, sans-serif; font-weight:500; font-size: 26pt; text-align:left; padding:30px 0 10px 30px;
}

.wrong {
	color:#ff0000; font-family:Tahoma, sans-serif; font-weight:500; font-size: 26pt; text-align:left; padding:30px 0 10px 30px;
	}
	
  ol, ul {
      list-style:none;
	  list-style-position:inside;
	  
  }
  
  
  
  
  p.pager {
      margin:5px 0 5px;
      font-weight:500;
	  font-size:2em;
	  line-height:2em;
      color:#999;
  }
  
  
  #choice-block {
      display:block;
      list-style:none;
      margin:-20px 15px 0 -15px;
      padding:0;
  }
  
  #submitbutton {
      -webkit-appearance: none;
  -webkit-border-radius: 5px;
      -moz-border-radius: 5px;
      border-radius: 5px;
  border:none;
  appearance:none;
  background:#005596;
	display:inline-block;
	text-decoration:none;
	padding: 12px;
		font-family: Tahoma, sans-serif;
		font-size: 14pt;
		color: #FFF;
		font-weight:bold;
		margin-top:20px;
  }
  #submitbutton:hover {
	  background-color:#f1cb00;
		text-decoration:none;
		-webkit-transition: 0.3s;
		-moz-transition: 0.3s;
		-ms-transition: 0.3s;
		-o-transition: 0.3s;
		transition: 0.3s;
  }
  
   #Submit {
      -webkit-appearance: none;
  -webkit-border-radius: 5px;
      -moz-border-radius: 5px;
      border-radius: 5px;
  border:none;
  appearance:none;
  background:#005596;
	display:inline-block;
	text-decoration:none;
	padding: 20px;
		font-family: Tahoma, sans-serif;
		font-size: 14pt;
		color: #FFF;
		font-weight:bold;
		margin-top:20px;
  }
  #Submit:hover {
	  background-color:#f1cb00;
		text-decoration:none;
		-webkit-transition: 0.3s;
		-moz-transition: 0.3s;
		-ms-transition: 0.3s;
		-o-transition: 0.3s;
		transition: 0.3s;
  }
  
  
  .choice-box {
      display:block;
      text-align:left;
      margin:8px auto;
      color: #005596;
	  font-weight: 300;
  	  font-size: 20px;
	  padding: 20px;
      cursor:pointer;
      -webkit-border-radius: 5px;
      -moz-border-radius: 5px;
      border-radius: 5px;
	  background:#e1e1e1;
  }
  
 @media only screen and (max-width: 900px) { 
 .correct {
	padding:20px 0 0 0;
}

.wrong {
	padding:20px 0 0 0;
	}

 }
  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id = "frame" role = "content" >

1 个答案:

答案 0 :(得分:1)

我已经更新了代码。也许这就是您所需要的,但是这不是此应用的最佳实现。

这是single-page application,当然,您可以使用jQuery,但是有更好的解决方案。最好的方法是使用其中一种框架(例如Angular,Vue.js,React等)。我强烈建议您获取有关框架的更多信息并开始使用它们。

我认为Vue.js的入门门槛较低,我建议阅读the doc,但每个框架都有自己的优势。

一些链接:

var quiztitle = "Quiz";


var quiz = [{
    "question": "Q1: What colour is the sky?",
    "choices": [
      "Blue",
      "Red",
      "Pink",
      "Green"
    ],
    "correct": "Blue",

  },
  {
    "question": "Q2: What colour is mustard?",
    "choices": [
      "Blue",
      "Yellow",
      "Green",
      "Red"
    ],
    "correct": "Yellow",
  },
  {
    "question": "Q3: What colour is grass?",
    "choices": [
      "Blue",
      "Yellow",
      "Red",
      "Green"
    ],
    "correct": "Green",
  },


];


var currentquestion = 0,
  score = 0,
  submt = true,
  picked;

jQuery(document).ready(function($) {


  function htmlEncode(value) {
    return $(document.createElement('div')).text(value).html();
  }


  function addChoices(choices) {
    if (typeof choices !== "undefined" && $.type(choices) == "array") {
      $('#choice-block').empty();
      for (var i = 0; i < choices.length; i++) {
        $(document.createElement('li')).addClass('choice choice-box').attr('data-index', i).text(choices[i]).appendTo('#choice-block');
      }
    }
  }

  function nextQuestion() {
    submt = true;
    $('#submitbutton').css('display', 'none');
    $('#form1').css('display', 'none');
    $('#explanation').empty();
    $('#question').text(quiz[currentquestion]['question']);
    $('#pager').text('Question ' + Number(currentquestion + 1) + ' of ' + quiz.length);
    addChoices(quiz[currentquestion]['choices']);
    setupButtons();


  }


  function processQuestion(choice) {
    if (quiz[currentquestion]['choices'][choice] == quiz[currentquestion]['correct']) {
      $('.choice').fadeIn(700, function() {
        $('.choice').eq(choice).css({
          'background-color': '#6C0',
          'color': '#ffffff',
          'font-weight': '300',
          'font-size': '20px',
          'padding': '20px'
        });
      });
      $('#explanation').fadeIn(700, function() {
        $('#explanation').html('<div class="correct"><i class="fal fa-check" style="font-family:FontAwesome; padding:30px 10px 30px 0;"></i> Correct!</div> ' + htmlEncode(quiz[currentquestion]['explanation']));
      });
      score++;
    } else {
      $('.choice').eq(choice).css({
        'background-color': '#ff0000',
        'color': '#ffffff',
        'font-weight': '300',
        'font-size': '20px',
        'padding': '20px'
      });
      $('#explanation').fadeIn(700, function() {
        $('#explanation').html('<div class="wrong"><i class="fal fa-times" style="font-family:FontAwesome; padding:30px 10px 30px 0;"></i> Incorrect.</div> ' + htmlEncode(quiz[currentquestion]['explanation']));
      });
    }
    currentquestion++;
    $('#submitbutton').fadeIn(700, function() {
      $('#submitbutton').html('NEXT QUESTION').on('click', function() {
        if (currentquestion == quiz.length) {
          endQuiz();
        } else {
          $(this).text('NEXT QUESTION').css({

          }).off('click');
          nextQuestion();
        }
      });
      $('#submitbutton').show();
    });
  }


  function setupButtons() {
    $('.choice').fadeIn(700, function() {
      $('.choice').on('mouseover', function() {
        $(this).css({
          'background-color': '#f1cb00',
          'color': '#005596',
          'font-weight': '300',
          'font-size': '20px',
          'padding': '20px'
        });
      });
    });
    $('.choice').fadeIn(700, function() {
      $('.choice').on('mouseout', function() {
        $(this).css({
          'background-color': '#e1e1e1',
          'color': '#005596',
          'font-weight': '300',
          'font-size': '20px',
          'padding': '20px'
        });
      });
    })
    $('.choice').fadeIn(700, function() {
      $('.choice').on('click', function() {
        if (submt) {
          submt = false;
          picked = $(this).attr('data-index');
          $('.choice').removeAttr('style').off('mouseout mouseover');
          $(this).css({

          });
          $('.choice').css({
            'cursor': 'default'
          });

          processQuestion(picked);
          $('#submitbutton').css({
            'padding': '20px'
          });

        }
      });
    })
  }


  function endQuiz() {
    $('#explanation').empty();
    $('#question').empty();
    $('.pager').hide();
    $('#choice-block').empty();
    $('#submitbutton').remove();

    /**
    * Added by Max
    */
		const percents = Math.round(score / quiz.length * 100);

		let $link = $(document.createElement('a'))
    	.css({
        'line-height': '20px',
        'text-align': 'center'
      });
    const $percents = $(document.createElement('h2'))
      .css({
        'line-height': '20px',
        'text-align': 'center'
      })
      .text(percents + '%');

		if (percents >= 70) {
      $link.text('Click here');
      $link.attr('href', 'https://google.com');
    } else {
      $link.text('Click here to repeat test');
      $link.attr('href', '#0')
      $link.on('click', ($event) => {
      	$event.preventDefault();
        
		  	clearContent();
        init();
      });
    }  

		$('#question').append($percents);
    $('#question').append($link);
    
    /**
    * End Added by Max
    */

    $('#form1').show();
  }

  // Added by Max
	function clearContent () {
    currentquestion = 0;
    score = 0;
    submt = true;
    picked = undefined;

  	$('#frame').empty();
  }


  function init() {
    //add title
    if (typeof quiztitle !== "undefined" && $.type(quiztitle) === "string") {
      $(document.createElement('header')).text(quiztitle).appendTo('#frame');
    } else {
      $(document.createElement('header')).text("Quiz").appendTo('#frame');
    }

    //add pager and questions
    if (typeof quiz !== "undefined" && $.type(quiz) === "array") {
      //add pager
      $(document.createElement('p')).addClass('pager').attr('id', 'pager').text('Question 1 of ' + quiz.length).appendTo('#frame');
      //add first question
      $(document.createElement('h2')).addClass('question').attr('id', 'question').text(quiz[0]['question']).appendTo('#frame');

      $(document.createElement('p')).addClass('explanation').attr('id', 'explanation').html('&nbsp;').appendTo('#frame');

      //questions holder
      $(document.createElement('ul')).attr('id', 'choice-block').appendTo('#frame').css({
        'padding-top': '20px'
      }) //add choices
      addChoices(quiz[0]['choices']);

      //add submit button
      $(document.createElement('div')).addClass('choice-box').attr('id', 'submitbutton').text('NEXT QUESTION').css({

      }).appendTo('#frame');

      setupButtons();
      $('#submitbutton').hide();
      $('#form1').hide();
    }
  }

  init();
});
header {
   background: #005596;
   color: #ffffff;
   padding: 20px;
   overflow: auto;
   font-size: 21pt;
   margin-bottom: 40px;
   -webkit-border-radius: 5px;
   -moz-border-radius: 5px;
   border-radius: 5px;
 }

 .correct {
   color: #6C0;
   font-family: Tahoma, sans-serif;
   font-weight: 500;
   font-size: 26pt;
   text-align: left;
   padding: 30px 0 10px 30px;
 }

 .wrong {
   color: #ff0000;
   font-family: Tahoma, sans-serif;
   font-weight: 500;
   font-size: 26pt;
   text-align: left;
   padding: 30px 0 10px 30px;
 }

 ol,
 ul {
   list-style: none;
   list-style-position: inside;
 }

 p.pager {
   margin: 5px 0 5px;
   font-weight: 500;
   font-size: 2em;
   line-height: 2em;
   color: #999;
 }

 #choice-block {
   display: block;
   list-style: none;
   margin: -20px 15px 0 -15px;
   padding: 0;
 }

 #submitbutton {
   -webkit-appearance: none;
   -webkit-border-radius: 5px;
   -moz-border-radius: 5px;
   border-radius: 5px;
   border: none;
   appearance: none;
   background: #005596;
   display: inline-block;
   text-decoration: none;
   padding: 12px;
   font-family: Tahoma, sans-serif;
   font-size: 14pt;
   color: #FFF;
   font-weight: bold;
   margin-top: 20px;
 }

 #submitbutton:hover {
   background-color: #f1cb00;
   text-decoration: none;
   -webkit-transition: 0.3s;
   -moz-transition: 0.3s;
   -ms-transition: 0.3s;
   -o-transition: 0.3s;
   transition: 0.3s;
 }

 #Submit {
   -webkit-appearance: none;
   -webkit-border-radius: 5px;
   -moz-border-radius: 5px;
   border-radius: 5px;
   border: none;
   appearance: none;
   background: #005596;
   display: inline-block;
   text-decoration: none;
   padding: 20px;
   font-family: Tahoma, sans-serif;
   font-size: 14pt;
   color: #FFF;
   font-weight: bold;
   margin-top: 20px;
 }

 #Submit:hover {
   background-color: #f1cb00;
   text-decoration: none;
   -webkit-transition: 0.3s;
   -moz-transition: 0.3s;
   -ms-transition: 0.3s;
   -o-transition: 0.3s;
   transition: 0.3s;
 }

 .choice-box {
   display: block;
   text-align: left;
   margin: 8px auto;
   color: #005596;
   font-weight: 300;
   font-size: 20px;
   padding: 20px;
   cursor: pointer;
   -webkit-border-radius: 5px;
   -moz-border-radius: 5px;
   border-radius: 5px;
   background: #e1e1e1;
 }

 @media only screen and (max-width: 900px) {
   .correct {
     padding: 20px 0 0 0;
   }
   .wrong {
     padding: 20px 0 0 0;
   }
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="frame" role="content">