简体   繁体   English

javascript:如何构建一个引用测验应用程序中变量的函数?

[英]javascript: How to build a function that refers to the variables in my Quiz app?

I recently built a small quiz application, it currently only has two questions. 我最近构建了一个小测验应用程序,它目前只有两个问题。 After all the questions are finished I would like for the app to present a page that says "You made it here" (eventually I'll add more). 在完成所有问题之后,我希望该应用程序显示一个页面,内容为“您在这里完成了”(最终,我将添加更多内容)。 However for some reason the final-function feedback of this code is not working. 但是由于某种原因,此代码的最终功能反馈无法正常工作。 Where am I going wrong? 我要去哪里错了?

$(document).ready(function () {  

var questions = [
{question: "Who is Zack Morris?",
 choices: ['images/ACslater.jpg','images/CarltonBanks.jpeg','images/ZachMorris.jpg'],
 quesNum: 1,
 correctAns: 2},

 {question: "Who is Corey Matthews?",
 choices: ['images/CoryMatthews.jpeg','images/EdAlonzo.jpg','images/Shawnhunter.jpg'],
 quesNum: 2,
 correctAns: 1},

 ];

 var userAnswer  //THis needs to be looked into
 var counter = 0;
 var score = 0;
 var html_string = '';
 var string4end = ''

//function to loop choices in HTML, updates counter, checks answer

var update_html = function(currentQuestion) {
    // put current question into a variable for convenience.

   // put the question string between paragraph tags
   html_string = '<p>' + currentQuestion.question + '</p>';  
   // create an unordered list for the choices
   html_string += '<ul>';
   // loop through the choices array
   for (var j = 0; j < currentQuestion.choices.length; j++) {
      // put the image as a list item
      html_string += '<li><img src="' + currentQuestion.choices[j] + '"></li>';
   }
   html_string += '</ul>';
   $('.setImg').html(html_string);
}

update_html(questions[0]);


$('.setImg li').on('click', function (e) {
   userAnswer = $(this).index();
   checkAnswer();
   counter++;
   update_html(questions[counter]);
   $('#score').html(score);
   showFinalFeedback();
});

//function to identify right question

function checkAnswer () 
{
   if (userAnswer === questions[counter].correctAns)
   {
      score=+100;  
   }
}

function showFinalFeedback ()
{
   if (counter === (questions.length+1))
   {

      string4end = '<p>' + 'You made it here!!!!' + '</p>';  
      $('.setImg').html(string4end);

   }

}




});

I agree with Vector that you either should start with 1 as Counter initialization or, to check 我同意Vector,您应该以1作为计数器初始化开始,或者检查

if (counter < questions.length) {
    return;
}
alert('You \'ve made it till here');

I also rewrote it in a form of a jquery plugin, maybe a handy comparison to your way of working? 我还以jquery插件的形式重写了它,也许与您的工作方式进行了方便的比较?

jsfiddle: http://jsfiddle.net/DEb7J/ jsfiddle: http : //jsfiddle.net/DEb7J/

;(function($) {
    function Question(options) {
        if (typeof options === 'undefined') {
            return;
        }

        this.chosen = -1;
        this.question = options.question;
        this.options = options.options;
        this.correct = options.correct;

        this.toString = function() {
            var msg = '<h3><i>' + this.question + '</i></h3>';
            for (var i = 0; i < this.options.length; i++) {
                msg += '<a id="opt' + i + '" class="answer toggleOff" onclick="$(this.parentNode).data(\'quizMaster\').toggle(' + i + ')">' + this.options[i] + '</a>';
            }
            return msg;
        };

        this.toggle = function(i) {
            var el = $('#opt' + i);
            if ($(el).hasClass('toggleOff')) {
                $(el).removeClass('toggleOff');
                $(el).addClass('toggleOn');
            } else {
                $(el).removeClass('toggleOn');
                $(el).addClass('toggleOff');
            }
        };
    }

    function Quiz(elem, options) {
        this.element = $(elem);
        this.lastQuestion = -1;
        this.questions = [];
        this.correct = 0;

        if (typeof options !== 'undefined' && typeof options.questions !== undefined) {
            for (var i = 0; i < options.questions.length; i++) {
                this.questions.push(new Question(options.questions[i]));
            }
        }

        this.start = function() {
            this.lastQuestion = -1;
            this.element.html('');
            for (var i = 0; i < this.questions.length; i++) {
                this.questions[i].chosen = -1;
            }
            this.correct = 0;
            this.next();
        };

        this.next = function() {
            if (this.lastQuestion >= 0) {
                var p = this.questions[this.lastQuestion];
                if (p.chosen === -1) {
                    alert('Answer the question first!');
                    return false;
                }
                if (p.chosen === p.correct) {
                    this.correct++;
                }
                $(this.element).html('');
            }
            this.lastQuestion++;
            if (this.lastQuestion < this.questions.length) {
                var q = this.questions[this.lastQuestion];
                $(this.element).html(q.toString());
                console.log(q.toString());
            } else {
                alert('you replied correct on ' + this.correct + ' out of ' + this.questions.length + ' questions');
                this.start();
            }
        };

        this.toggle = function(i) {
            if (this.lastQuestion < this.questions.length) {
                var q = this.questions[this.lastQuestion];
                q.toggle(q.chosen);
                q.toggle(i);
                q.chosen = i;
            }
        };
    }

    $.fn.quizMaster = function(options) {
        if (!this.length || typeof this.selector === 'undefined') {
            return;
        }
        var quiz = new Quiz($(this), options);
        quiz.start();
        $(this).data('quizMaster', quiz);
        $('#btnConfirmAnswer').on('click', function(e) {
            e.preventDefault();
            quiz.next();
        });
    };
}(jQuery));

$(function() {
    $('#millionaire').quizMaster({
        questions: [
            { 
                question: 'Where are the everglades?',
                options: ['Brazil','France','USA','South Africa'],
                correct: 2
            },
            { 
                question: 'Witch sport uses the term "Homerun"?',
                options: ['Basketball','Baseball','Hockey','American Football'],
                correct: 1
            }
        ]
    });
});

Hey guys thanks for your help. 大家好,谢谢您的帮助。 I was able to use the following work around to ensure everything worked: 我能够使用以下解决方法来确保一切正常:

$('.setImg').on('click', 'li', function () {  
userAnswer = $(this).index();
checkAnswer();
counter++;
$('#score').html(score);

if (counter < questions.length)
     {
       update_html(questions[counter]);

      }
else{
         showFinalFeedback();
      }    
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM