2016-10-17 3 views
1

여기에 언급 된 것처럼 퀴즈 응용 프로그램을 만들어서 자바 스크립트를 배우려고합니다. Learn Javascript Properly 더 고급 퀴즈를 수행하는 데 문제가 있습니다. 템플릿 엔진으로 Handlebars를 사용하고 있습니다. 질문을 외부 JSON 파일에 저장했으며, 입력은 라디오 버튼으로 구성되어 있습니다.숫자가 올바르게 증가하지 않습니다.

index.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); 
}) 

:

<!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 의견에 모든 것을 설명했습니다 , 문제는 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 
    } 
] 
+0

int를 구문 분석하거나 증분을 float으로 바꿉니다. – guradio

+0

나는 그것을 수행했지만 여전히 작동하지 않습니다. – Akar

+0

문제를 보여주는 간단한 데모를 만들 수 있습니까? – guradio

답변

1

이 코드에 여러 가지 문제가 있습니다 그들은 다음과 같습니다 start 기능에

  • 당신이 배열 인덱스와 일치하는 if 조건 표현식을 변경해야하는 자바 스크립트에서 0부터 시작하고 배열의 마지막 요소는 인덱스 questions.length - 1입니다.
  • start 함수에서 먼저 새 질문을 렌더링 한 다음이 단계에서 이미 삭제 된 선택한 요소에 대해 DOM을 쿼리합니다. 따라서 먼저 handleQuestion이 필요하고 새로운 것을 렌더링하십시오.
  • 는 또한 handleQuestion 첫번째 렌더링에서 실행되지 않아야하기 때문에
  • (후 렌더링) 마지막 단계 currentIndex 증분 코드를 이동 사실 수단이 외래 Quiz.currentIndex && Quiz.handleQuestion(questions); 첨가 "currentIndex가 0 인 경우를되는 부울에 표현식은 false으로 변환되고 부울 조건의 오른쪽 부분 인 Quiz.handleQuestion(questions) "을 실행하지 마십시오.

    자바 스크립트

    // 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; 
        } 
    } 
    

    을 라이브 데모 :

  • 가 선택한 입력의 숫자 값을 가져하려면 결과 코드는 다음과 같이한다 parseInt($("input[name=choices]:checked", "#choicesForm").val(), 10)

사용해야합니다

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

+0

좋은 답변이지만, 여전히 마지막 답변을 포함하지 않습니다. 그래서 모든 질문에 올바르게 대답하더라도 결과는 5 점 만점에 4 점이됩니다. 그래도 여전히 대부분의 문제를 해결했습니다. 감사합니다! – Akar

관련 문제