跳过数组中的对象&无法显示按钮标记值

时间:2015-07-17 14:20:05

标签: javascript jquery

我正在创建一个包含6个基本问题的测验应用程序。 4个答案供您选择。当我运行该应用程序时,第二个问题被忽略了“在美国排名第一的最受欢迎的食物是什么?”(有选择)。另外,h3 id =" final"将不会在游戏结束时显示。我相信我存储的userInput不正确。

main.js:

$(document).ready(function() {

  var numberCorrect = 0;
  var currentQuestion = 0;

  var questions = [
    {
    question: 'The average American lives in a _ square foot house.',
    choices: [2500, 1500, 1800, 2200],
    rightAnswer: 2
    },
    {
    question: 'What is ranked as the number one favorite food in America?',
    choices: ["Cheese", "Steak", "Chicken", "Popcorn"],
    rightAnswer: 1
    },
    {
    question: 'How many credit cards does the average American have?',
    choices: [2, 1, 3, 5],
    rightAnswer: 0
    },
    {
    question: 'The average American worker stays at each of its jobs for how long?',
    choices: ["4.4 years", "2 years", "5.6 years", "3.8 years"],
    rightAnswer: 0
    },
    {
    question: 'What is the average American household carry in debt?',
    choices: ["$45,000", "$20,000", "$60,000", "$75,000"],
    rightAnswer: 3
    },
    {
    question: 'The recommended sugar intake per day is 22 grams. How much does the average American intake?',
    choices: [30, 43, 77, 85],
    rightAnswer: 2
    }
  ];

  function nextQuestion() {
    $('.questionContent h1').remove();
    $('.choiceButton').remove();
    if (currentQuestion <= 6) {
        var htmlQuestion = questions[currentQuestion].question;
        var htmlChoices = questions[currentQuestion].choices;
        for (var i = 0, len = htmlChoices.length; i < len; i++) {
            $(".question").html(htmlQuestion)
            var answerChoice = '<button class="choiceButton" type="submit" value="' + i + '">' + htmlChoices[i] + '</button>';
            $(".questionContainer").append(answerChoice);
        }
    } 
    else {
        $(".container h2").remove();
        $(".questionContainer").remove();
        $(".submitButton").remove();
        $(".question").remove();
        if (numberCorrect >= 1) {
              $(".questionContainer").html('<h3 id="final">Congratulations!</h3> <p>You correctly answered ' + numberCorrect + ' questions out of 6</p>');
        } else {
              $(".questionContainer").html('<h3 id="final">Sorry.. you answered no questions correctly</h3>');
        }
    }
  }

  function answerQuestion() {
  $(".questionContainer").on('click', 'button', function(event) {
    var answer = questions[currentQuestion].rightAnswer;
    var userInput = $(this).val();
    if (answer === userInput) {
        console.log($(this).val()) 
        numberCorrect++;  
    };
    });
  }

  $(".playButton").one("click", function() {
    $(".playButton").hide();
    $(".submitButton").show().css('display', 'block');
    $(".container h2").css('display', 'inline-block');
    nextQuestion();
  });

  $(".submitButton").on("click", function() {
    currentQuestion++;
    nextQuestion();
    answerQuestion();
    if (currentQuestion <= 6) {
        $(".questionNumber").text(currentQuestion);
    }
  });  
});  

HTML:

<html>
<head>
<meta charset="UTF-8" />
<title>The Average American Game</title>
<link href='http://fonts.googleapis.com/css?family=Questrial|Maven+Pro:400,500,700|PT+Sans+Caption:400,700|Open+Sans:400,600,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
 <div class="main-container">
    <header>
      <h1>THE AVERAGE AMERICAN</h1>
    </header>
    <div class="container">
        <div class="stars">
            <li><img class="star1" src="https://cloud.githubusercontent.com/assets/12075685/8212453/d71b22c4-14e9-11e5-9207-69a5ad35f976.png" alt="star"/></li>
            <li><img class="star2" src="https://cloud.githubusercontent.com/assets/12075685/8212453/d71b22c4-14e9-11e5-9207-69a5ad35f976.png" alt="star"/></li>
            <li><img class="star3" src="https://cloud.githubusercontent.com/assets/12075685/8212453/d71b22c4-14e9-11e5-9207-69a5ad35f976.png" alt="star"/></li>
            <li><img class="star4" src="https://cloud.githubusercontent.com/assets/12075685/8212453/d71b22c4-14e9-11e5-9207-69a5ad35f976.png" alt="star"/></li>
            <li><img class="star5" src="https://cloud.githubusercontent.com/assets/12075685/8212453/d71b22c4-14e9-11e5-9207-69a5ad35f976.png" alt="star"/></li>
            <li><img class="star6" src="https://cloud.githubusercontent.com/assets/12075685/8212453/d71b22c4-14e9-11e5-9207-69a5ad35f976.png" alt="star"/></li>
        </div>
        <h2>Question <span class="questionNumber">1</span></h2>
        <div class="questionContent">
            <h1>Are You Ready to Play?</h1>
            <h3 class="question"></h3>
            <div class="questionContainer"></div>
            <button class="playButton">Let's Play!</button>
            <button class="submitButton">submit</button>
        </div>
    </div>
    <footer>
    </footer>
   </div>
  </body>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="main.js"></script>
</html>

1 个答案:

答案 0 :(得分:0)

我很久以前使用基本的javascript模块模式做了类似的事情。我知道,这与您在代码方面所做的完全不同,但更好,更清晰,更易读。

请注意,我已经声明了一个名为QUIZ的全局模块,其中包含一个公共属性:名为QUIZ.init的方法。此外,它还使用匿名函数的闭包来维护私有内部状态。此外,我们可以使用此模式轻松导入所需的全局变量。看看演示,看看你是否可以根据自己的需要进行调整。

var questions = [
    {
        question: 'The average American lives in a _ square foot house.',
        choices: [2500, 1500, 1800, 2200],
        rightAnswer: 2
    },
    {
        question: 'What is ranked as the number one favorite food in America?',
        choices: ["Cheese", "Steak", "Chicken", "Popcorn"],
        rightAnswer: 1
    },
    {
        question: 'How many credit cards does the average American have?',
        choices: [2, 1, 3, 5],
        rightAnswer: 0
    },
    {
        question: 'The average American worker stays at each of its jobs for how long?',
        choices: ["4.4 years", "2 years", "5.6 years", "3.8 years"],
        rightAnswer: 0
    },
    {
        question: 'What is the average American household carry in debt?',
        choices: ["$45,000", "$20,000", "$60,000", "$75,000"],
        rightAnswer: 3
    },
    {
        question: 'The recommended sugar intake per day is 22 grams. How much does the average American intake?',
        choices: [30, 43, 77, 85],
        rightAnswer: 2
    }
];

var QUIZ = (function($) {
    var $context = $(".container");
    var index = 0;
    var correctAnswers = 0;
    var totalQuestions = questions.length;
    
    function startQuiz (btn) {
        $(btn).hide();
        createQuestion();
    }
    function validateAnswer (choice) {
        if (parseInt($(choice).val(), 10) === questions[index]["rightAnswer"]) {
            correctAnswers++;
            console.log(correctAnswers);
        }
        if (index === totalQuestions - 1) {
            complete();
            return;
        }
        index++;
        createQuestion();
    }
    function createQuestion () {
        var $question = $("<h2/>", {
            text: questions[index]["question"]
        });
        var $answers = $();
        $.each(questions[index]["choices"], function(i, val) {
            $answers = $answers.add( $("<button/>", {
                'class': "choiceButton",
                'value': i,
                'text': val
            }) );
        });

        $context.find(":not(.startQuiz)").remove();
        $context.append($question);
        $context.append($answers);
    }
    function complete () {
        var msg = correctAnswers ? "You have " + correctAnswers + " correct answers!": "You've got no correct asnwers!";
        $context
        .find(":not(.startQuiz)").remove().end()
        .prepend($("<h3/>", {
            id: "final",
            text: msg
        }))
        .end().find(".startQuiz").text("Restart Quiz").show();
        index = 0;
        correctAnswers = 0;
    }
    function init () {
        $context.on("click", ".startQuiz", function() {
            startQuiz(this);
        });
        
        $context.on("click", ".choiceButton", function() {
            validateAnswer(this);
        });
    }
    return {
        init: init
    };
}(jQuery)).init();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
    <button class="startQuiz">Start Quiz</button>
</div>