javascript:如何构建一个函数来引用我的Quiz应用程序中的变量

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

本文关键字:我的 引用 Quiz 应用程序 变量 函数 何构建 构建 javascript 一个      更新时间:2023-09-26

我最近构建了一个小测验应用程序,它目前只有两个问题。所有的问题都完成后,我想为应用程序呈现一个页面,说"你做到了这里"(最终我会添加更多)。然而,由于某些原因,这段代码的最终函数反馈不起作用。我哪里做错了?

$(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);
   }
}


});

我同意Vector的观点,你要么从1开始作为Counter初始化,要么检查

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

我还以jquery插件的形式重写了它,也许是一个方便的比较你的工作方式?

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="answerswer 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
            }
        ]
    });
});

嘿,谢谢你们的帮助。我能够使用以下工作来确保一切正常:

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