数字没有正确递增

时间:2016-10-17 10:01:56

标签: javascript jquery json

我正在尝试通过创建一个类似于此处提到的测验应用程序来学习Javascript:Learn Javascript Properly我无法尝试进行更高级的测验,我使用Handlebars作为我的模板引擎。我已将问题存储在外部JSON文件中,输入只是一堆单选按钮。

的index.html

<!DOCTYPE html>
<html>
<head>
    <title>Quiz Application</title>
    <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="container">
    <div id="quiz">
    </div>
    <button id="next-question">Next Question</button>   
</div>

<!-- Templates -->
<script id="titleTemplate" type="text/x-handlebars-template">
    <div id="quiz-question">{{ title }}</div>
</script>
<script id="choicesTemplate" type="text/x-handlebars-template">
    <div id="choices">
        <form id="choicesForm">
                {{#each choices}}
                <div class="choice">
                    <input type="radio" name="choices" id="choice{{@index}}" value="{{ @index }}">
                    <label for="choice{{ @index }}" value="{{ @index }}">{{ this }}</label>
                </div> 
                {{/each}}
        </form>
    </div>
</script>

<script type="text/javascript" src="js/jquery-3.1.0.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>

我在评论中解释了一切 的 app.js

 "use strict";
var Render = {
    question: function(questions, currentIndex) {
        var titleTemplate   = Handlebars.compile($("#titleTemplate").html());
        var choicesTemplate  = Handlebars.compile($("#choicesTemplate").html());
        var currentQuestion = questions[currentIndex];
        Render.title(titleTemplate, currentQuestion);
        Render.choices(choicesTemplate, currentQuestion);
    },
    title: function(titleTemplate, currentQuestion) {
        $("#quiz").html(titleTemplate(currentQuestion));
    },
    choices: function(choicesTemplate, currentQuestion) {
        $('#quiz-question').append(choicesTemplate(currentQuestion));
    },
};

var Quiz = {
    // Tracks the current questions
    currentIndex: 0,

    // The number of the correct answers
    // I want to increment this when the user 
    // answers the correct question, for some reason it doesn't increment.
    correctAnswers: 0,

    // I first call this method to get the questions from JSON file
    // since you can no longer have synchronous requests
    getQuestions: function() {
        $.getJSON('questions.json', Quiz.start);
    },
    // Starts the quiz
    start: function(questions) {
        // Check if the user is passed the last question
        // in this case, if 6 > 5
        if(Quiz.currentIndex + 1 > questions.length) {
            Quiz.displayFinalScore(questions);
        } else {
            // Render the next question using the currentIndex
            Render.question(questions, Quiz.currentIndex);
            Quiz.handleQuestion(questions);       
        }
    },

    handleQuestion: function(questions) {
        // Get's the correct answer from the JSON
        var correctAnswer = questions[Quiz.currentIndex].correctAnswer;
        // Check if the radio button is checked
        if($("input[name=choices]:checked", "#choicesForm") == correctAnswer) {
            // This doesn't increment like it suppose to
            // It still stays at 0.
            Quiz.correctAnswers +=  1;
        }

        // Increment the index to change to the next question
        Quiz.currentIndex += 1;
    },
    displayFinalScore: function(questions) {
        // Simple console log
        console.log("You have scored: " + Quiz.correctAnswers + " out of " + questions.length);
    }
};

$(function() {
    Quiz.getQuestions();    
    $("#next-question").on("click", Quiz.getQuestions);
})

正如你所看到的,我在评论中已经解释过,问题在于增加correctAnswers由于某种原因,即使我选择了正确的它也没有达到比较两个变量的程度从单选按钮回答。

questions.json

[
    {
        "title":"When did the programming language C++ came out?",
        "choices":[
            1997,
            1995,
            2000,
            1998
        ],
        "correctAnswer":3
    },
    {
        "title":"When Node.js came out?",
        "choices":[
            2010,
            2011,
            2009,
            2006
        ],
        "correctAnswer":2
    },
    {
        "title":"What brand of laptop do I have?",
        "choices":[
            "HP",
            "Acer",
            "Dell",
            "Lenovo"
        ],
        "correctAnswer":0
    },
    {
        "title":"How old am I?",
        "choices":[
            12,
            20,
            9,
            16
        ],
        "correctAnswer":3
    },
    {
        "title":"How old is Google?",
        "choices":[
            12,
            20,
            18,
            16
        ],
        "correctAnswer":2
    }
]

1 个答案:

答案 0 :(得分:1)

您的代码存在以下几个问题:

  • start函数中,您应该更改if条件表达式以匹配数组索引,这些索引在JavaScript中从0开始,而数组的最后一个元素具有索引questions.length - 1
  • start函数中,您首先呈现新问题,然后查询所选元素的DOM,该元素已在此阶段销毁。所以你需要先handleQuestion,然后才能渲染新的。{/ li>
  • 我还将currentIndex增量代码移到了最后一步(渲染后)
  • 由于handleQuestion不应该在第一次渲染时执行,我添加了这个异域Quiz.currentIndex && Quiz.handleQuestion(questions);,这实际上意味着:“如果currentIndex为0,则布尔表达式中的变换为{{ 1}},不要运行布尔条件的正确部分,即false“。
  • 要获取所选输入的数值,您应使用Quiz.handleQuestion(questions)

生成的代码应如下所示:

<强>的JavaScript

parseInt($("input[name=choices]:checked", "#choicesForm").val(), 10)

现场演示

https://plnkr.co/edit/03IGvb6IZiw6QbziUpw6?p=preview