2016-10-12 2 views
1

Мне удалось создать викторину с помощью javascript и html. Это простая викторина с 5 вопросами, так как теперь только решение для вопроса появляется, когда пользователь ошибается, я попытался добавить функцию для других вопросов, но он не будет работать, я хочу узнать, как я прохожу через все пять вопросов, чтобы дать решение в нижней части каждого неправильного ответа, заданного пользователем.Как использовать циклы в викторине javascript

<HEAD> 
 

 
<style type="text/css"> 
 
<!-- 
 
.bgclr {background-color: white; color: black; font-weight: bold;} 
 
--> 
 

 
\t .hidden { 
 
\t \t display: none; 
 
\t } 
 
\t 
 
\t .visible { 
 
\t \t display: block; 
 
\t } 
 
\t 
 
</style> 
 

 
<script language="JavaScript"> 
 

 

 
// Insert scooter questions number of questions 
 
var numQues = 5; 
 

 
// Insert number of choices in each question 
 
var numChoi = 3; 
 

 
// Insert number of questions displayed in answer area 
 
var answers = new Array(5); 
 

 
// Insert answers to questions 
 
answers[0] = "Keep to the left side of the road far as is safe."; 
 
answers[1] = "Road which cross."; 
 
answers[2] = "When a traffic officer order you to do so."; 
 
answers[3] = "Traffic circle where right of way is applicable."; 
 
answers[4] = "(i), (ii) and (iii)"; 
 
answers[5] = "A marked pedestrian crossing ahead."; 
 

 

 
function getScore(form) { 
 
\t showCorrectAnswers(); 
 

 
    var score = 0; 
 
    var currElt; 
 
    var currSelection; 
 
    for (i=0; i<numQues; i++) { 
 
    currElt = i*numChoi; 
 
    for (j=0; j<numChoi; j++) { 
 
     currSelection = form.elements[currElt + j]; 
 
     if (currSelection.checked) { 
 
     if (currSelection.value == answers[i]) { 
 
      score++; 
 
\t \t break; 
 
     } 
 
     } 
 
    } 
 
    } 
 
    score = Math.round(score/numQues*100); 
 
    form.percentage.value = score + "%"; 
 
    var correctAnswers = ""; 
 
    for (i=1; i<=numQues; i++) { 
 
    correctAnswers += i + ". " + answers[i-1] + "\r\n"; 
 
    } 
 
    
 
    form.solutions.value = correctAnswers; 
 
} 
 

 
function showCorrectAnswers() { 
 
\t var q1Inputs = document.querySelectorAll('.q1-inputs input'); 
 
\t var correctAnswer = document.querySelector('.q1-inputs span'); 
 
\t var correct = correctAnswer.textContent; 
 
\t q1Inputs.forEach(function(element) { 
 
\t \t if (element.checked) { 
 
\t \t \t if (element.value !== correct) { 
 
\t \t \t \t correctAnswer.classList.remove('hidden'); 
 
\t \t \t } else { 
 
\t \t \t \t correctAnswer.classList.add('hidden'); 
 
\t \t \t } 
 
\t \t } 
 
\t }); 
 
} 
 

 
// End --> 
 
</script> 
 

 
</HEAD> 
 

 
<!-- STEP TWO: Copy this code into the BODY of your HTML document --> 
 

 
<BODY> 
 

 
<h3>Scooter quiz by johnson</h3> 
 

 
<form name="quiz"> 
 

 

 

 

 
1. Which rule is considered the most important RULE OF THE ROAD in South Africa? 
 
<ul class="q1-inputs" style="margin-top: 1pt"> 
 
    <li><input type="radio" name="q1" value="Always be courteous and considerate towards fellow road users.">Always be courteous and considerate towards fellow road users.</li> 
 
    <li><input type="radio" name="q1" value="Do not exceed the speed limit.">Do not exceed the speed limit.</li> 
 
    <li><input type="radio" name="q1" value="Keep to the left side of the road far as is safe.">Keep to the left side of the road far as is safe.</li> 
 
    <span class="hidden" style="color:red;">Keep to the left side of the road far as is safe.</span> 
 
    
 
    
 
</ul> 
 

 

 

 

 
2. Sign L9 warns you about... ahead. 
 

 
<ul style="margin-top: 1pt"> 
 
    <li><input type="radio" name="q2" value="Where you are also not allowed to park."> Where you are also not allowed to park..</li> 
 
    <li><input type="radio" name="q2" value="A railway crossing">A railway crossing</li> 
 
    <li><input type="radio" name="q2" value="Road which cross">Road which cross</li> 
 
</ul> 
 

 

 

 
3.Under what circumstances, if any, are you allowed to drive your motor motor vehicle on the right-hand side of a public road with traffic moving in both directions? 
 
<ul style="margin-top: 1pt"> 
 
    <li><input type="radio" name="q3" value="When you switch the emergency lights of your vehicle on.">When you switch the emergency lights of your vehicle on.</li> 
 
    <li><input type="radio" name="q3" value="When a traffic officer order you to do so.">When a traffic officer order you to do so.</li> 
 
    <li><input type="radio" name="q3" value="Under no circumstance.">Under no circumstance.</li> 
 
</ul> 
 

 

 

 
4.Sign CC9 is found at .. 
 
<ul style="margin-top: 1pt"> 
 
    <li><input type="radio" name="q4" value="Traffic circle where right of way is applicable.">Traffic circle where right of way is applicable.</li> 
 
    <li><input type="radio" name="q4" value="Dangerous place where roadwork is being done.">Dangerous place where roadwork is being done.</li> 
 
    <li><input type="radio" name="q4" value="Sharp curve to the right.">Sharp curve to the right.</li> 
 
</ul> 
 

 
5.You may not obtain a learner’s license if... 
 

 
<ul style="margin-top: 1pt"> 
 
    <li><input type="radio" name="q5" value="A first-aid post."> A first-aid post.</li> 
 
    <li><input type="radio" name="q5" value="A railway crossing">A railway crossing</li> 
 
    <li><input type="radio" name="q5" value="Road which cross">Road which cross</li> 
 
</ul> 
 

 

 

 

 

 

 

 

 
<input type="button" value="Get score" onClick="getScore(this.form)"> 
 
<input type="reset" value="Clear answers"> 
 
<p> Score = <strong><input class="bgclr" type="text" size="5" name="percentage" disabled></strong><br><br> 
 
Correct answers:<br> 
 
<textarea class="bgclr" name="solutions" wrap="virtual" rows="10" cols="100" disabled> 
 
</textarea> 
 
</form>

ответ

0

JavaScript

var getScoreButton = document.getElementById("getScore"), 
quizSections = document.getElementById("quizForm").querySelectorAll("ul"), 
quizScore = document.getElementById("percentage"), 
quizSolutions = document.getElementById("solutions"), 
answers = new Array(5), 
score = 0, 
solutions = ''; 

// Insert answers to questions 
answers[0] = "Keep to the left side of the road far as is safe."; 
answers[1] = "Road which cross."; 
answers[2] = "When a traffic officer order you to do so."; 
answers[3] = "Traffic circle where right of way is applicable."; 
answers[4] = "(i), (ii) and (iii)"; 
answers[5] = "A marked pedestrian crossing ahead."; 

function checkAnswers(source) { 

    source.forEach(function(section, index){ 

     var selectedAnswer = section.querySelector("input:checked"); 

     if(selectedAnswer){ 

      if(answers[index] === selectedAnswer.value){ 

       score+=1; 
      }else{ 

       solutions+= (index+1) + '. ' + answers[index] + "\n"; 
      } 
     }else{ 
      solutions+= (index+1) + '. ' + answers[index] + "\n"; 
     } 
    }); 

    quizScore.value = score; 
    quizSolutions.value = solutions; 

    score = 0; 
    solutions = ''; 
} 


getScoreButton.addEventListener("click", function(){ 

    checkAnswers(quizSections); 
}); 

обновление HTML (добавлены некоторые идентификаторы)

<input type="button" value="Get score" id="getScore"> <input type="reset" value="Clear answers"> <p> Score = <strong><input class="bgclr" type="text" size="5" name="percentage" id="percentage" disabled></strong><br><br> Correct answers:<br> <textarea class="bgclr" name="solutions" id="solutions" wrap="virtual" rows="10" cols="100" disabled>

+0

на lucian, я должен заменить все мои js с вашим обновленным js? –

+0

вы можете поместить код snipet, чтобы я мог запустить его с этого сайта –

+0

да, замените ваш код js на эту часть. Также замените кусок html – n1kkou

-3

Вы можете использовать .getAttribute ('значение') instesd из .value

UPDATE обновить

function showCorrectAnswers() { 
var x = ['q1-inputs', 'q2-inputs','q3-inputs', 'q4-inputs', 'q5-inputs']; 
for(value of x){ 
    var q1Inputs = document.querySelectorAll('.'+value+' input'); 
    var correctAnswer = document.querySelector('.'+value+' span'); 
    var correct = correctAnswer.textContent; 
    q1Inputs.forEach(function(element) { 

    if (element.checked) { 
    if (element.getAttribute('value') !== correct) { 
    correctAnswer.classList.remove('hidden'); 
    } else { 
    correctAnswer.classList.add('hidden'); 
    } 
    }}); 
} 
} 
+0

Это не ответ. Насколько я могу судить, все, что вы сделали, это изменение отступов исходного кода и разметки. – meagar

+0

Я использовал getAttribute ('значение'), где, как и в коде для передачи, это значение., Которое давало пользователю ошибку – rohit180

+0

Тогда скажите так же. Вы представили свой ответ в почти невозможном для использования формате. Никто не заинтересован в чтении всего блога кода, чтобы выявить различия. – meagar

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