recherche

Maison  >  Questions et réponses  >  le corps du texte

标题重写:Un bug dans mon quiz entraîne une augmentation infinie du score lorsque la bonne réponse est enfoncée plusieurs fois

Donc, je crée une animation CSS pour mon diplôme, et j'ai configuré le quiz pour qu'il passe en boucle sur des questions avec des réponses spécifiques, le quiz est entièrement fonctionnel, etc... Cependant, j'ai remarqué que lorsque c'est correct, en appuyant sur une réponse plusieurs fois, le score augmentera, même si la réponse a déjà été sélectionnée et que l'augmentation initiale du score a été ajoutée. Cela commence par un écran avec du texte dessus pour fournir le récit du jeu que nous créons, ce qui est également ce qui est attendu.

Il s'agit d'une configuration de page unique où toutes les pages se trouvent à l'intérieur d'un conteneur parent et parcourent les pages des conteneurs enfants.

Codez au style en utilisant JQuery, HTML et CSS.

    // --------------------------Multiple Choice Page------------------------//

    $("#start-button").click(function() {
      $("#beginning-screen").remove();
      ;})

      $("#start-button-quiz").click(function() {
        $("#beginning-screen-quiz").remove();
        ;})

    $('#answer1').click(function(){
      $(this).addClass("selected");
      setTimeout(function() {
          checkAnswer(1);
      },1000);
    });
    $('#answer2').click(function(){
      $(this).addClass("selected")
      setTimeout(function() {
          checkAnswer(2);
      },1000);
    });
    $('#answer3').click(function(){
      $(this).addClass("selected")
      setTimeout(function() {
          checkAnswer(3);
      },1000);
    });

    $('#next-btn').click(function(){
      nextQuestion();
    });
    nextQuestion();

});

// --------------------------- Multiple Choice Page functions and variables -------------------------------------

// Study Page

var currentBox = 1;
var numBoxes = $('.text-box').length;


// variables here

var quizData = [
  {question:"If the size of a battery in a complete circuit is increased:",
   answers:["the current decreases","the current increases","the voltage stays the same"],
   correctAnswer:2,
   feedback:"An increase in voltage will increase the current flowing in a circuit (if nothing else is changed) Click to next page find out more."
  },
   {question:"The current in a series circuit containing two bulbs:",
   answers:["is the same at every place in the circuit","is larger nearer the battery","is larger between the bulbs"],
   correctAnswer:1,
   feedback:"This is an important point to remember about a series circuit. Click to next page find out more."
  },
  {question:"Two identical bulbs are in parallel in a complete circuit. If one breaks:",
   answers:["the other stays on","the other goes off","the other bulb is brighter"],
   correctAnswer:1,
   feedback:"This is a benefit of a parallel circuit, it is usually easier to find out which component has broken as the rest still work"
  },
  {question:"Wires are usually coated in plastic because:",
   answers:["plastic is an insulator","plastic can be lots of different colours","plastic helps the wires conduct electricity"],
   correctAnswer:1,
   feedback:"Wires used to be covered with rubber as an insulator but rubber perishes faster than plastic."
  },
  {question:"Which of the following statements is true?",
   answers:["A voltmeter is connected in series to measure voltage.","Different sized bulbs in parallel have the same current flowing through them.","In a parallel circuit with four identical bulbs, the current is shared equally between them."],
   correctAnswer:3,
   feedback:"If the four bulbs were NOT identical, the current would still be shared out, but not equally."
  },
  {question:"Wires are normally made from copper. This is because:",
   answers:["copper has a high resistance","copper is cheap","copper is a very good conductor of electricity"],
   correctAnswer:3,
   feedback: "It is also very malleable and can therefore easily be bent to go round corners."
  },
  {question:"Two identical bulbs are in parallel in a complete circuit. A third identical bulb is connected in parallel. What happens?",
   answers:["All the bulbs are dimmer","All the bulbs are the same brightness","The third bulb is brighter"],
   correctAnswer:2,
   feedback:"Adding identical bulbs in parallel uses more current but brightness stays the same."
  },
];


var currentQuestion = 0;
var totalQuestions = quizData.length;
var score = 0;

function showQuestion(){
$("#question").html(quizData[currentQuestion-1].question);
$("#answer1").html(quizData[currentQuestion-1].answers[0]);
$("#answer2").html(quizData[currentQuestion-1].answers[1]);
$("#answer3").html(quizData[currentQuestion-1].answers[2]);
$("#feedback").html(quizData[currentQuestion-1].feedback);
}

function nextQuestion(){
currentQuestion++;

if(score >= 60){
  $("#answersAndFeedback").addClass('hidden');
  $("#question").addClass('hidden');
  $("#game-over").removeClass('hidden');
  $('.p2-button').removeClass('hidden');
  $("#next-btn").addClass("hidden");
  return;
}

if(currentQuestion > totalQuestions){
  // end of quiz
  $("#game-over").removeClass('hidden');
  return;
}

showQuestion();

// hide feedback and next button
$("#next-btn").addClass("hidden");
$("#feedback").addClass("hidden");
// remove all incorrect, correct classes on answer buttons
$('.answer-box').removeClass("correct incorrect");

// add restart button if score is under 60
if(score < 60){
  $("#feedback").append('<button id="restart-btn" onclick="location.reload();">Restart Quiz</button>');
  $('.p2-button').addClass('hidden');
}
}


function checkAnswer(selectedAnswer){
var theCorrectAnswer = quizData[currentQuestion-1].correctAnswer;
// remove the grey selected class
$('.answer-box').removeClass("selected");

// turn the boxes red or green depending on if they are the correct answer
$( ".answer-box" ).each(function( index ) {
  if((index+1)==theCorrectAnswer){
    $( this ).addClass("correct");
  } else {
    $( this ).addClass("incorrect");
  }
});

if(selectedAnswer==theCorrectAnswer){
  // got it correct
  score += 10;
  $(".score").html(score);
} else {
  // got it wrong so do nothing
}
// show feedback and next button
$("#next-btn").removeClass("hidden");
$("#feedback").removeClass("hidden");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!-- Multiple Choice Page -->

<div class="page-multiple-choice">
    <div id="beginning-screen-quiz">
        <h1 id="heading-quiz">Oh no! it looks like you have been locked out of the computer system. You will have to take this quiz in order to regain access, you must get a score of 60 in order to bypass the security system.</h1>
        <button id="start-button-quiz">Hack into security</button>
    </div>
    <h1>Multiple Choice Quiz</h1>
    <div class="p2-button button">
        Fix the circuit
    </div>
    <div class="p-menu-button button">
        Go back to menu
    </div>
    <div id="wrapper">
        <div id="question">Sample question here</div>
        <div id="answersAndFeedback">
            <div id="answer1" class="answer-box">Answer 1</div>
            <div id="answer2" class="answer-box">Answer 2</div>
            <div id="answer3" class="answer-box">Answer 3</div>
            <div id="feedback" class="hidden">Feedback goes here</div>
        </div>
        <div class="score">0</div>
        <div id="next-btn" class="hidden">next</div>
        <div id="game-over" class="hidden">Congratulations! Continue to the next page!</div>
    </div>
</div>

Toute explication sur la façon de résoudre ce problème serait grandement appréciée, même si les utilisateurs ne pourront peut-être pas trouver le bug, je veux quand même couvrir toutes les bases et m'assurer qu'il est corrigé pour l'intégrité de la conception du jeu.

J'ai essayé d'ajouter :

// Disable all answer boxes to prevent further selection
  $('.answer-box').prop('disabled', true);

Cependant, il y avait un bug dans le mode développeur de Google, donc je l'ai supprimé, mais cela n'a toujours pas arrêté les problèmes que je rencontrais, ce qui a également causé plus de problèmes, ne me permettant pas d'appuyer sur le bouton suivant, et désactivera le processus de sélection après avoir appuyé complètement sur la première bonne réponse.

P粉312195700P粉312195700301 Il y a quelques jours473

répondre à tous(2)je répondrai

  • P粉207969787

    P粉2079697872024-02-22 14:23:01

    Je pense que vous devez parcourir votre boîte de réponse.

    En adaptant l'exemple de cette question et la réponse ci-dessous ( boucle jQuery sur des éléments de même classe ), vous devez changer votre code JS en :

    $('.answer-box').each(function(){
         $(this).prop('disabled', true);
     });

    répondre
    0
  • P粉398117857

    P粉3981178572024-02-22 00:36:47

    Ici, j'ai ajouté calculleçon lorsque les fractions augmentent

    Essayez ceci JSFiddle

    function checkAnswer(selectedAnswer) {
        var theCorrectAnswer = quizData[currentQuestion - 1].correctAnswer;
        // remove the grey selected class
        $('.answer-box').removeClass("selected");
    
        // turn the boxes red or green depending on if they are the correct answer
        $(".answer-box").each(function (index) {
            if ((index + 1) == theCorrectAnswer) {
                $(this).addClass("correct");
            } else {
                $(this).addClass("incorrect");
            }
        });
    
        if (selectedAnswer == theCorrectAnswer && $(".score").hasClass('calculated') == false) {
            // got it correct
            score += 10;
            $(".score").html(score);
            $(".score").addClass('calculated');
        } else {
            // got it wrong so do nothing
        }
        // show feedback and next button
        $("#next-btn").removeClass("hidden");
        $("#feedback").removeClass("hidden");
    }

    et ajoutez nextQuestion() au début de

    $(".score").removeClass('calculated');

    répondre
    0
  • Annulerrépondre