簡體   English   中英

在第二輪應用運行期間事件被調用兩次

[英]event gets called twice during second round of app run

我有一個帶分數計數器的測驗應用程序。 一切都在第一次運行中起作用,但是在第二次運行中回答第二個問題后,事件將兩次調用計分計數器(第二次運行意味着我在第一次執行中使用了“重新開始測驗”按鈕)。 它被調用兩次,並從那里開始兩次添加點。 表示該事件被綁定兩次,我不確定在哪里或如何阻止它。

if (answerIsCorrect) {
  scoreCounter();
  responseMsg = `
    <h2>Correct</h2>
    <p>On to the next.</p>
    <button role='button' type="button" class='button js-button-subsequent'>Submit & Next
    </button>`;
}

這是整個代碼中唯一被調用的地方,看起來像這樣:

function scoreCounter() {
  scoreCount += 10;
  $(".js-score-counter").text(scoreCount);
}

請簽出CodePen

在您單擊下一個按鈕之后,單擊任何一個單選按鈕,原始代碼將多次檢查答案。

function evalChosenAnswer() {
  $(".js-quizform-questions").on("click", "input[type=radio]", event => {
    console.log($(event.currentTarget))
    let answer = $(event.currentTarget)
      .closest(".css-answers")
      .children("label")
      .text();
    renderFeedback(answer);
  });
}

因此,將其替換為以下代碼,該代碼在單擊下一步按鈕后僅檢查一次答案,

function evalChosenAnswer() {
  $(".js-quizform-questions").on("click", ".js-button-next", event => {

    // check if answer is right or not when click the next button
    let answer = $(event.currentTarget)              // the next button
                 .siblings()                         // find fieldset
                 .find(".css-answers input:checked") // find checked radio button
                 .siblings()                         // find the label
                 .text();                            // get the text
    renderFeedback(answer);
  });
}

並從function renderFeedback刪除相同的委托單擊處理程序

function renderFeedback(answer) {
  $(".js-quizform-questions").on("click", ".js-button-next", () => {
    ... codes ...
  });
}

function renderFeedback(answer) {
  ... codes ...
}

 console.clear(); const DB = [{ question: "What is the closest star to our own sun?", answers: ["Proxima Centauri", "Our sun", "Betelgeuse", "Sirius "], correctAnswer: "Proxima Centauri" }, { question: "Which US President made the first telephone call to the moon?", answers: [ "Henry Truman", "Richard Nixon", "Franklin D. Roosevelt", "Jimmy Carter" ], correctAnswer: "Richard Nixon" }, { question: "Betelgeuse and Rigel are the two giant stars in which constellation?", answers: ["Andromeda", "Aries", "Virgo", "Orion"], correctAnswer: "Orion" }, { question: "In our solar system, which planet has the shortest day?", answers: ["Earth", "Venus", "Jupiter", "Mercury"], correctAnswer: "Jupiter" }, { question: "Hale-Bopp is classified as which type of small Solar System body?", answers: ["Comet", "Asteroid", "Meteoroid", "Meteor"], correctAnswer: "Comet" }, { question: "What is the name for the disc-shaped region of icy bodies that extends from Neptune to about 55 astronomical units from the Sun?", answers: [ "Orion's Belt", "Copernicus' Belt", "Caeser's Belt", "Kuiper Belt" ], correctAnswer: "Kuiper Belt" }, { question: "In our solar system which two planets are known as ice giants?", answers: [ "Venus & Mars", "Neptune & Pluto", "Uranus & Neptune", "Jupiter & Uranus" ], correctAnswer: "Uranus & Neptune" }, { question: '"Mare Tranquillitatis" is the Latin name for what feature found on Earth\\'s moon?', answers: [ "Sea of Tranquility", "Chilled Mahi", "Tranquil Mars", "Calm horse" ], correctAnswer: "Sea of Tranquility" }, { question: "Who were there first two astronauts that landed on the moon in 1969?", answers: [ 'Buzz Lightyear & Lance "Woody" Armstrong', "Neil Armstrong & Buzz Aldrin", "Tom Aldrin & Neil Diamond", "Buzz Adderrall & Neil Aldrin" ], correctAnswer: "Neil Armstrong & Buzz Aldrin" }, { question: "The Great Red Spot is a gigantic storm located on which planet in our solar system?", answers: ["Earth", "Mars", "Jupiter", "Venus"], correctAnswer: "Jupiter" } ]; let scoreCount = 0; let numberIncr = 0; function renderIntro() { $(".js-quizform-intro").show(); $(".js-quizform-questions").hide(); $(".js-feedback-page").hide(); $(".js-quizform-evaluation").hide(); } function showNext() { $(".js-quizform-submit").on("click", event => { $(".js-quizform-intro").hide(); $(".js-quizform-questions").show(); $(".js-quizform-questions").html(renderQuestion()); }); } function renderQuestion() { increaseCount(); return ` <h2>${DB[numberIncr - 1].question}</h2> <form id='form'> <fieldset> <div class='css-answers'> <input id='answer1' type='radio' name='answer' required> <label for='answer1'>${DB[numberIncr - 1].answers[0]}</label> </div> <div class='css-answers'> <input id='answer2' type='radio' name='answer' required> <label for='answer2'>${DB[numberIncr - 1].answers[1]}</label> </div> <div class='css-answers'> <input id='answer3' type='radio' name='answer' required> <label for='answer3'>${DB[numberIncr - 1].answers[2]}</label> </div> <div class='css-answers'> <input id='answer4' type='radio' name='answer' required> <label for='answer4'>${DB[numberIncr - 1].answers[3]}</label> </div> </fieldset> <button role='button' type="button" class='button js-button-next'>Submit & Next</button> </form> `; } function evalChosenAnswer() { $(".js-quizform-questions").on("click", ".js-button-next", event => { // check if answer is right or not when click the next button let answer = $(event.currentTarget).siblings().find(".css-answers input:checked").siblings().text(); renderFeedback(answer); }); } function renderFeedback(answer) { $(".js-quizform-questions") .empty() .hide(); const answerIsCorrect = checkAnswer(answer); let responseMsg = ""; if (answerIsCorrect) { responseMsg = `<h2>Correct</h2> <p>On to the next.</p> <button role='button' type="button" class='button js-button-subsequent'>Submit & Next</button>`; scoreCounter(); } else { responseMsg = `<h2>Incorrect,</h2> <p>but the universe has many answers.</p> <button role='button' type="button" class='button js-button-subsequent'>Submit & Next</button>`; } $(".js-feedback-page") .show() .html(responseMsg); } function checkAnswer(answer) { return answer === DB[numberIncr - 1].correctAnswer; } function scoreCounter() { scoreCount += 10; $(".js-score-counter").text(scoreCount); } function renderSubsequent() { $(".js-feedback-page").on("click", ".js-button-subsequent", () => { if (numberIncr === 3) { $(".js-feedback-page").hide(); $(".js-quizform-evaluation") .show() .html(renderScore); } else { $(".js-feedback-page").hide(); $(".js-quizform-questions") .show() .html(renderQuestion); } }); } function increaseCount() { numberIncr++; $(".js-question-counter").text(numberIncr); } function renderScore() { return ` <h2>You did it!</h2> <h3>Your final score is ${scoreCount}.</h3> <p>If you want to try again, click the button below</p> <button role='button' type="button" class='button js-button-reload'>Submit & Next</button> `; } function reload() { $(".js-quizform-evaluation").on("click", ".js-button-reload", () => { $(".js-question-counter").text(0); $(".js-score-counter").text(0); scoreCount = 0; numberIncr = 0 renderIntro(); }); } function startApp() { renderIntro(); showNext(); // renderFeedback() evalChosenAnswer(); renderSubsequent(); reload(); } $(startApp); 
 body { margin: 0; } header { align-items: center; background: #eee; display: flex; height: 70px; justify-content: center; } .counters { display: flex; justify-content: space-evenly; } .quizdiv { align-items: center; display: flex; flex-direction: column; justify-content: center; margin: 1.5em 0; } .quizform { border: 1px solid #e3e3e3; padding: 1em 2em; width: 50%; } .controls { display: flex; justify-content: center; } .button { border-radius: 4px; border-width: 0; outline: none; padding: 1em; } .js-button-next { width: 10em; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <main role='main'> <div class='counters'> <p>Question: <span class='js-question-counter'>0</span> / 10</p> <p>Score: <span class="js-score-counter">0</span></p> </div> <div class="quizdiv"> <div class="quizform js-quizform-intro"> <h2>Welcome, Willkommen, Bonjour, Buon giorno, Hola</h2> <p>Test your knowledge in everything space-related. Just click the button below and start the 10 question quiz.</p> <div class="controls"> <button role='button' class="button js-quizform-submit">Start Quiz</button> </div> </div> <div class="quizform js-quizform-questions"></div> <div class="quizform js-feedback-page"></div> <div class="quizform js-quizform-evaluation"></div> </div> </main> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM