Javascript 数字没有正确递增

Javascript 数字没有正确递增,javascript,jquery,json,Javascript,Jquery,Json,我正试图通过创建一个测验应用程序来学习Javascript,就像这里提到的:我在尝试更高级的测验时遇到了困难,我正在使用把手作为我的模板引擎。我将问题存储在一个外部JSON文件中,输入只是一组单选按钮 index.html: <!DOCTYPE html> <html> <head> <title>Quiz Application</title> <link href="https://fonts.googleap

我正试图通过创建一个测验应用程序来学习Javascript,就像这里提到的:我在尝试更高级的测验时遇到了困难,我正在使用把手作为我的模板引擎。我将问题存储在一个外部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>
 "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);
})
[
    {
        "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
    }
]
正如我在评论中所解释的,问题在于增加
正确答案
,因为某些原因,即使我从单选按钮中选择了正确答案,它也无法比较两个变量

问题。json

<!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>
 "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);
})
[
    {
        "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
    }
]

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

  • start
    函数中,您应该更改
    if
    条件表达式以匹配数组索引,在JavaScript中,数组索引从
    0
    开始,数组的最后一个元素具有index
    questions.length-1
  • start
    函数中,首先呈现新问题,然后查询所选元素的DOM,该元素在此阶段已被销毁。因此,您需要首先处理问题,然后才渲染新问题
  • 我还将
    currentIndex
    增量代码移动到最后一步(渲染后)
  • 由于
    handleQuestion
    不应在第一次渲染时执行,因此我添加了这个奇异的
    quick.currentIndex&&quick.handleQuestion(问题)
    ,这实际上意味着:“如果
    currentIndex
    为0,在布尔表达式中转换为
    false
    ,则不要运行布尔条件的正确部分,即
    quick.handleQuestion(questions)
  • 要获取所选输入的数值,应使用
    parseInt($(“输入[name=choices]:checked”,“#choicesForm”).val(),10)
生成的代码应如下所示:

JavaScript

// Starts the quiz
start: function(questions) {
    // Check if the user is passed the last question
    // in this case, if 5 >= 5
    if(Quiz.currentIndex >= questions.length) {
        Quiz.displayFinalScore(questions);
    } else {
        Quiz.currentIndex && Quiz.handleQuestion(questions);
        // Render the next question using the currentIndex
        Render.question(questions, Quiz.currentIndex++);
    }
},

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


将其解析为int或float为increment我也这样做了,但仍然不起作用。您可以创建一个简单的演示来显示您的问题吗?检查此计算结果:$(“input[name=choices]:checked”,“#choicesForm”)==correctAnswer。它可能为false,因此不会命中增量部分。您在没有if语句的情况下尝试过吗?如果它在没有If语句的情况下递增,那么问题就出在条件上,你可以把注意力集中在这一点上,而不是看其他地方。答案不错,但它仍然不计算最后一个答案。因此,即使我正确回答了所有问题,结果将是五分之四。不过,你还是解决了大部分问题,谢谢!