2016-03-11 2 views
1

Я начинающий в Javascript Я хочу создать базовое приложение для викторины javascript с переключателями. В конце викторины я хочу получить сообщение с окончательным счетом. Я не могу отобразить окончательный результат. Это то, что я закодированы еще .. HTML:Невозможно отобразить итоговый счет в викторине Javascript

var allQuestions = [{ 
 
    question: "Who is the Prime Minister of the United Kingdom?", 
 
    choices: ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"], 
 
    correctAnswer: 0 
 
    }, 
 

 
    { 
 
    question: "Who is the Prime Minister of India?", 
 
    choices: ["Rahul Gandhi", "Arvind Kejrival", "Narendra Damodardas Modi"], 
 
    correctAnswer: 2 
 
    }, 
 

 
    { 
 
    question: "Who is the Prime Minister of America?", 
 
    choices: ["Donald Trump", "Barack Obama", "Hilary Clinton"], 
 
    correctAnswer: 2 
 
    } 
 
]; 
 

 
var correctAnswers = 0; 
 
$(document).ready(function() { 
 
    var currentquestion = 0; 
 

 
    $('#question').html(allQuestions[currentquestion].question); 
 
    $('label[for=option0]').html(allQuestions[currentquestion].choices[0] + "<br/>"); 
 
    $('label[for=option1]').html(allQuestions[currentquestion].choices[1] + "<br/>"); 
 
    $('label[for=option2]').html(allQuestions[currentquestion].choices[2] + "<br/>"); 
 

 
    $("#next").click(function() { 
 
    if ($("input[name=option]:checked").val() == allQuestions[currentquestion].correctAnswer) { 
 
     correctAnswers++; 
 
    }; 
 
    currentquestion++; 
 
    if (currentquestion < allQuestions.length) { 
 
     $('#question').html(allQuestions[currentquestion].question); 
 
     $('label[for=option0]').html(allQuestions[currentquestion].choices[0] + "<br/>"); 
 
     $('label[for=option1]').html(allQuestions[currentquestion].choices[1] + "<br/>"); 
 
     $('label[for=option2]').html(allQuestions[currentquestion].choices[2] + "<br/>"); 
 
     if (currentquestion == allQuestions.length - 1) { 
 
     $('#next').html("Submit"); 
 
     $('#next').click(function() { 
 
     /*If I comment out the following if statement, but retain correctAnswers++, I do get alert message,but the result is obviously wrong*/ 
 
      if ($("input[name=option]:checked").val() == allQuestions[currentquestion].correctAnswer) { 
 
      correctAnswers++; 
 
      } 
 
      alert(correctAnswers); 
 
      //alert("Your Score is " + correctAnswers + " out of " + currentquestion + " and your percentage is " + (correctAnswers*100/currentquestion) + "%"); 
 
     }); 
 

 
     } 
 

 
    }; 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> 
 
<body> 
 
    <div> 
 
    <h3 id="question"></h3> 
 
    <form id="form"> 
 
     <input type="radio" name="option" value="0" id="option0" checked> 
 
     <label for='option0'> 
 
     <br/> 
 
     </label> 
 
     <input type="radio" name="option" value="1" id="option1"> 
 
     <label for='option1'> 
 
     <br/> 
 
     </label> 
 
     <input type="radio" name="option" value="2" id="option2"> 
 
     <label for='option2'> 
 
     <br/> 
 
     </label> 
 
    </form> 
 
    </div> 
 
    <br/> 
 
    <a href="#" id="next" class="button hvr-bounce-to-right">Next</a> 
 

 
</body>

Пожалуйста, помогите! здесь JSFiddle.

ответ

0

Если вы прокомментируете, если и correctAnswers ++ предложение, ваш код работает правильно.

  /*If I comment out the following if statement, but retain correctAnswers++, I do get alert message,but the result is obviously wrong*/ 
      /*if ($("input[name=option]:checked").val() == allQuestions[currentquestion].correctAnswer) { 
      correctAnswers++; 
      }*/ 
      alert(correctAnswers); 
      alert("Your Score is " + correctAnswers + " out of " + currentquestion + " and your percentage is " + (correctAnswers*100/currentquestion) + "%"); 
+0

Это замечательный человек. Не могли бы вы рассказать/объяснить свой ответ? – Rashid

+0

Конечно, когда пользователь нажимает кнопку отправки, переменная correctAnswers уже имеет правильное значение. В этот момент текущее условие равно 3. Таким образом, при сравнении allQuestions [currentquestion] .correctAnswer не определен, и ваш исходный код завершает свое исполнение без успеха. –

+0

Если вы показываете предупреждение с правильными ответами перед или вместо сравнения, вы увидите, что его значение равно 3. alert (correctAnswers) –

1

я исправить код

jsFiddle

проблема здесь

if($("input[name=option]:checked").val()==allQuestions[currentquestion].correctAnswer){ 
    correctAnswers++; 
} 
+0

4 хорошие ответы, когда есть 3 вопроса? У меня все в порядке ! –

+0

Он по-прежнему не работает. Конечные результаты ошибочны. Даже с тремя правильными ответами я получаю 2 в поле оповещения – Rashid

+0

@ PierreC., О, извините, я этого не заметил. Но делает ли это какие-либо разница с моей проблемой – Rashid

1

Здесь у вас есть рабочая демо.

var allQuestions = [{ 
 
    question: "Who is the Prime Minister of the United Kingdom?", 
 
    choices: ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"], 
 
    correctAnswer: 0 
 
    }, 
 

 
    { 
 
    question: "Who is the Prime Minister of India?", 
 
    choices: ["Rahul Gandhi", "Arvind Kejrival", "Narendra Damodardas Modi"], 
 
    correctAnswer: 2 
 
    }, 
 

 
    { 
 
    question: "Who is the Prime Minister of America?", 
 
    choices: ["Donald Trump", "Barack Obama", "Hilary Clinton"], 
 
    correctAnswer: 2 
 
    } 
 
]; 
 

 

 
$(document).ready(function() { 
 
    var currentquestion = 0; 
 
    var correctAnswers = 0; 
 
    var done = false; 
 

 
    $('#question').html(allQuestions[currentquestion].question); 
 
    $('label[for=option0]').html(allQuestions[currentquestion].choices[0] + "<br/>"); 
 
    $('label[for=option1]').html(allQuestions[currentquestion].choices[1] + "<br/>"); 
 
    $('label[for=option2]').html(allQuestions[currentquestion].choices[2] + "<br/>"); 
 

 
    $("#next").click(function() { 
 
    if ($("input[name=option]:checked").val() == allQuestions[currentquestion].correctAnswer) { 
 
     correctAnswers++; 
 
    }; 
 

 
    if (done) { 
 
     alert(correctAnswers); 
 
    } else { 
 
     currentquestion++; 
 
     if (currentquestion < allQuestions.length) { 
 
     $('#question').html(allQuestions[currentquestion].question); 
 
     $('label[for=option0]').html(allQuestions[currentquestion].choices[0] + "<br/>"); 
 
     $('label[for=option1]').html(allQuestions[currentquestion].choices[1] + "<br/>"); 
 
     $('label[for=option2]').html(allQuestions[currentquestion].choices[2] + "<br/>"); 
 
     if (currentquestion == allQuestions.length - 1) { 
 
      $('#next').html("Submit"); 
 
      done = true; 
 
     } 
 
     } 
 
    } 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> 
 
<body> 
 
    <div> 
 
    <h3 id="question"></h3> 
 
    <form id="form"> 
 
     <input type="radio" name="option" value="0" id="option0" checked> 
 
     <label for='option0'> 
 
     <br/> 
 
     </label> 
 
     <input type="radio" name="option" value="1" id="option1"> 
 
     <label for='option1'> 
 
     <br/> 
 
     </label> 
 
     <input type="radio" name="option" value="2" id="option2"> 
 
     <label for='option2'> 
 
     <br/> 
 
     </label> 
 
    </form> 
 
    </div> 
 
    <br/> 
 
    <a href="#" id="next" class="button hvr-bounce-to-right">Next</a> 
 

 
</body>

+0

спасибо.Проблема решена – Rashid

+0

Отлично! Имейте в виду, что ответ с зеленой проверкой не самый лучший. Событие клика внутри события клика на самом деле не очень хорошее. – NiZa

+0

любая конкретная причина для этого ?, я нашел @PierreC. наиболее явным и понятным, поэтому я пометил его. – Rashid

1

Вот мое решение вашей проблемы. Вы увеличили currentQuestion за дополнительное время после последнего вопроса.

https://jsfiddle.net/k7874vjn/5/

if(currentquestion<allQuestions.length){ 
       $('#question').html(allQuestions[currentquestion].question); 
       $('label[for=option0]').html(allQuestions[currentquestion].choices[0]+"<br/>"); 
       $('label[for=option1]').html(allQuestions[currentquestion].choices[1]+"<br/>"); 
       $('label[for=option2]').html(allQuestions[currentquestion].choices[2]+"<br/>"); 
       if(currentquestion==allQuestions.length-1){ 
        $('#next').html("Submit"); 
        $('#next').click(function(){ 
         if($("input[name=option]:checked").val()==allQuestions[currentquestion].correctAnswer){ 
          correctAnswers++; 
         } 
         alert(correctAnswers); 
         //alert("Your Score is " + correctAnswers + " out of " + currentquestion + " and your percentage is " + (correctAnswers*100/currentquestion) + "%"); 
        }); 

       } else 
      currentquestion++; //MOVED HERE 

      }; 
+0

Получение 4 хороших ответов на 3 вопроса. Я не думаю, что код был плохим. Просто установив дважды нажатие на клик, см. [Мой ответ] (http://stackoverflow.com/a/35943497/5994091) –

+0

@henrikmerlander, который не работает. Вначале требуется два клика для перехода к следующему вопросу и morevoer , окончательный результат отображает 2, даже когда все три ответа были правильными – Rashid

+0

Мне очень жаль, я не входил в правильный ответ за последний вопрос. Мой плохой. Корри. И спасибо человеку. Но все же первый следующий требует двух нажмите, чтобы перейти к следующему вопросу. – Rashid

1

Проблема заключается в том, что вы установили другой щелчок обратного вызова событий на следующей кнопки в то время как первый все еще активен.

$('#next').unbind("click"); Просто добавьте так:

$('#next').html("Submit"); 
$('#next').unbind("click"); 
$('#next').click(... 

Это удалить щелчок слушателя на кнопке, прежде чем установить новый.

Фрагмент кода:

var allQuestions = [{ 
 
    question: "Who is the Prime Minister of the United Kingdom?", 
 
    choices: ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"], 
 
    correctAnswer: 0 
 
    }, 
 

 
    { 
 
    question: "Who is the Prime Minister of India?", 
 
    choices: ["Rahul Gandhi", "Arvind Kejrival", "Narendra Damodardas Modi"], 
 
    correctAnswer: 2 
 
    }, 
 

 
    { 
 
    question: "Who is the Prime Minister of America?", 
 
    choices: ["Donald Trump", "Barack Obama", "Hilary Clinton"], 
 
    correctAnswer: 2 
 
    } 
 
]; 
 

 
var correctAnswers = 0; 
 
$(document).ready(function() { 
 
    var currentquestion = 0; 
 

 
    $('#question').html(allQuestions[currentquestion].question); 
 
    $('label[for=option0]').html(allQuestions[currentquestion].choices[0] + "<br/>"); 
 
    $('label[for=option1]').html(allQuestions[currentquestion].choices[1] + "<br/>"); 
 
    $('label[for=option2]').html(allQuestions[currentquestion].choices[2] + "<br/>"); 
 

 
    $("#next").click(function() { 
 
    if ($("input[name=option]:checked").val() == allQuestions[currentquestion].correctAnswer) { 
 
     correctAnswers++; 
 
    }; 
 
    currentquestion++; 
 
    if (currentquestion < allQuestions.length) { 
 
     $('#question').html(allQuestions[currentquestion].question); 
 
     $('label[for=option0]').html(allQuestions[currentquestion].choices[0] + "<br/>"); 
 
     $('label[for=option1]').html(allQuestions[currentquestion].choices[1] + "<br/>"); 
 
     $('label[for=option2]').html(allQuestions[currentquestion].choices[2] + "<br/>"); 
 
     if (currentquestion == allQuestions.length - 1) { 
 
     $('#next').html("Submit"); 
 
     $('#next').unbind("click"); 
 
     $('#next').click(function() { 
 
     /*If I comment out the following if statement, but retain correctAnswers++, I do get alert message,but the result is obviously wrong*/ 
 
      if ($("input[name=option]:checked").val() == allQuestions[currentquestion].correctAnswer) { 
 
      correctAnswers++; 
 
      } 
 
      alert(correctAnswers); 
 
      //alert("Your Score is " + correctAnswers + " out of " + currentquestion + " and your percentage is " + (correctAnswers*100/currentquestion) + "%"); 
 
     }); 
 

 
     } 
 

 
    }; 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> 
 
<body> 
 
    <div> 
 
    <h3 id="question"></h3> 
 
    <form id="form"> 
 
     <input type="radio" name="option" value="0" id="option0" checked> 
 
     <label for='option0'> 
 
     <br/> 
 
     </label> 
 
     <input type="radio" name="option" value="1" id="option1"> 
 
     <label for='option1'> 
 
     <br/> 
 
     </label> 
 
     <input type="radio" name="option" value="2" id="option2"> 
 
     <label for='option2'> 
 
     <br/> 
 
     </label> 
 
    </form> 
 
    </div> 
 
    <br/> 
 
    <a href="#" id="next" class="button hvr-bounce-to-right">Next</a> 
 

 
</body>

+0

попытался сделать это .. он все еще показывает 2, когда все три ответа верны – Rashid

+0

Ну, у меня есть 3, когда я запускаю свой фрагмент кода ... вы проверяете первый ответ в вопросе 1, а затем последний ответ для остальных? –

+0

Мне очень жаль, я не ввел правильный ответ на последний вопрос. Мой плохой. Корри. И спасибо человеку. – Rashid

Смежные вопросы