Кнопки в скрипте нажимаются без моего разрешения? Javascript Общая игра - PullRequest
0 голосов
/ 14 октября 2019

Я работаю над тем, чтобы связать все это. Моя игра пустяков обернута в функцию, и кнопки запускаются сами по себе, но по порядку. Поэтому, если я нажму A, то #optionB #optionC и #optionD запустят все самостоятельно. Кроме того, я могу выбрать только один вариант (#optionA), чтобы сделать следующий вопрос. Вот ссылка Jsfiddle Однако ссылка не работает должным образом, как если бы вы запускали ее в VScode и т. Д., Но весь код предоставлен в ссылке JSfiddle, поэтому ее легко скопировать и вставить, потому что онаКак вы можете видеть, много кода я пытался обернуть кликами в функцию, но это не решило проблему.

(function() {
  let arr = [$("#optionA"), $("#optionB"), $("#optionC"), $("#optionD")];
  let randArr = arr[Math.floor(arr.length * Math.random())];
  let btnNext = $("#btnNext");
  let answer = randArr;
  let question = "";
  let answerReal;
  let optionA = $("#optionA");
  let optionB = $("#optionB");
  let optionC = $("#optionC");
  let optionD = $("#optionD");
  var count = 0;
  let correct = 0;
  let incorrect = 0;
  let unanswered = 0;
  function startGame() {
    $(btnNext).on("click", function nextQuestion() {
      count++;
      console.log(count);
      if (count === 10) {
        $("#container").hide();
        $("#score").show();
      }
      //   function shuffle() {  //---------this function was called to randomize my array(var arr), however it's not needed---
      //     var currentarr = arr.length;
      //     var index, temp;

      //     while (currentarr > 0) {
      //       index = Math.floor(Math.random() * currentarr);
      //       currentarr--;

      //       temp = arr[currentarr];
      //       arr[currentarr] = arr[index];
      //       arr[index] = temp;
      //     }
      //   }
      (function($) {
        //-----------------this function shuffles all the DOM elements after its been called (look down below)------------
        $.fn.shuffle = function() {
          var allElems = this.get(),
            getRandom = function(max) {
              return Math.floor(Math.random() * max);
            },
            shuffled = $.map(allElems, function() {
              var random = getRandom(allElems.length),
                randEl = $(allElems[random]).clone(true)[0];
              allElems.splice(random, 1);
              return randEl;
            });

          this.each(function(i) {
            $(this).replaceWith($(shuffled[i]));
          });

          return $(shuffled);
        };
      })(jQuery);
      //-----------------------here we call the DOM elements to be shuffled---------------------------------------------------
      $("#answers button").shuffle();
      fetch("http://jservice.io/api/random")
        .then(function(response) {
          if (response.status !== 200) {
            console.log(
              "Looks like there was a problem. Status Code: " + response.status
            );
            return;
          }

          // Examine the text in the response
          response.json().then(function(data) {
            //------------------------------FETCHING THE API----------------------------------------------
            console.log(data);
            answerReal = data[0].answer;
            question = data[0].question;
            console.log(question + ": " + answer);
            $("#question").html(question);
            // shuffle($("#answers"));
            console.log(arr);
            $("#optionA").html(answerReal);
            $("#optionA").addClass("secretwinner");
            console.log(answerReal);
          });
        })
        .catch(function(err) {
          console.log("Fetch Error :-S", err);
        });
      fetch("http://jservice.io/api/random")
        .then(function(response) {
          if (response.status !== 200) {
            console.log(
              "Looks like there was a problem. Status Code: " + response.status
            );
            return;
          }

          // Examine the text in the response
          response.json().then(function(data) {
            console.log(data);
            answerNonReal = data[0].answer;
            $("#optionB").html(answerNonReal);
            $("#optionB").addClass("notasecretwinner");
            console.log(answerNonReal); //-----------------------------FETCHING THE API----------------------------------------
          });
        })
        .catch(function(err) {
          console.log("Fetch Error :-S", err);
        });
      fetch("http://jservice.io/api/random")
        .then(function(response) {
          if (response.status !== 200) {
            console.log(
              "Looks like there was a problem. Status Code: " + response.status
            );
            return;
          }

          // Examine the text in the response
          response.json().then(function(data) {
            console.log(data);
            answerNonReal = data[0].answer;
            $("#optionC").html(answerNonReal);
            $("#optionC").addClass("notasecretwinner");
            console.log(answerNonReal); //------------------------------FETCHING THE API---------------------------------------
          });
        })
        .catch(function(err) {
          console.log("Fetch Error :-S", err);
        });
      fetch("http://jservice.io/api/random")
        .then(function(response) {
          if (response.status !== 200) {
            console.log(
              "Looks like there was a problem. Status Code: " + response.status
            );
            return;
          }

          // Examine the text in the response
          response.json().then(function(data) {
            console.log(data);
            answerNonReal = data[0].answer;
            $("#optionD").html(answerNonReal);
            $("#optionD").addClass("notasecretwinner");
            console.log(answerNonReal); //-------------------------------FETCHING THE API--------------------------------------
          });
        })
        .catch(function(err) {
          console.log("Fetch Error :-S", err);
        });
    });
  } //---------------------------------------------------------END-------------------------------------------------------------
  function renderQuestion() {
    count++;
    console.log(count);
    if (count === 10) {
      $("#container").hide();
      $("#score").show();
    }
    (function($) {
      //-----------------this function shuffles all the DOM elements after its been called (look down below)------------
      $.fn.shuffle = function() {
        var allElems = this.get(),
          getRandom = function(max) {
            return Math.floor(Math.random() * max);
          },
          shuffled = $.map(allElems, function() {
            var random = getRandom(allElems.length),
              randEl = $(allElems[random]).clone(true)[0];
            allElems.splice(random, 1);
            return randEl;
          });

        this.each(function(i) {
          $(this).replaceWith($(shuffled[i]));
        });

        return $(shuffled);
      };
    })(jQuery);
    //-----------------------here we call the DOM elements to be shuffled---------------------------------------------------
    $("#answers button").shuffle();
    fetch("http://jservice.io/api/random")
      .then(function(response) {
        if (response.status !== 200) {
          console.log(
            "Looks like there was a problem. Status Code: " + response.status
          );
          return;
        }

        // Examine the text in the response
        response.json().then(function(data) {
          //------------------------------FETCHING THE API----------------------------------------------
          console.log(data);
          answerReal = data[0].answer;
          question = data[0].question;
          console.log(question + ": " + answer);
          $("#question").html(question);
          console.log(arr);
          $("#optionA").html(answerReal);
          $("#optionA").addClass("secretwinner");
          console.log(answerReal);
        });
      })
      .catch(function(err) {
        console.log("Fetch Error :-S", err);
      });
    fetch("http://jservice.io/api/random")
      .then(function(response) {
        if (response.status !== 200) {
          console.log(
            "Looks like there was a problem. Status Code: " + response.status
          );
          return;
        }

        // Examine the text in the response
        response.json().then(function(data) {
          console.log(data);
          answerNonReal = data[0].answer;
          $("#optionB").html(answerNonReal);
          $("#optionB").addClass("notasecretwinner");
          console.log(answerNonReal); //-----------------------------FETCHING THE API----------------------------------------
        });
      })
      .catch(function(err) {
        console.log("Fetch Error :-S", err);
      });
    fetch("http://jservice.io/api/random")
      .then(function(response) {
        if (response.status !== 200) {
          console.log(
            "Looks like there was a problem. Status Code: " + response.status
          );
          return;
        }

        // Examine the text in the response
        response.json().then(function(data) {
          console.log(data);
          answerNonReal = data[0].answer;
          $("#optionC").html(answerNonReal);
          $("#optionC").addClass("notasecretwinner");
          console.log(answerNonReal); //------------------------------FETCHING THE API---------------------------------------
        });
      })
      .catch(function(err) {
        console.log("Fetch Error :-S", err);
      });
    fetch("http://jservice.io/api/random")
      .then(function(response) {
        if (response.status !== 200) {
          console.log(
            "Looks like there was a problem. Status Code: " + response.status
          );
          return;
        }

        // Examine the text in the response
        response.json().then(function(data) {
          console.log(data);
          answerNonReal = data[0].answer;
          $("#optionD").html(answerNonReal);
          $("#optionD").addClass("notasecretwinner");
          console.log(answerNonReal); //-------------------------------FETCHING THE API--------------------------------------
        });
      })
      .catch(function(err) {
        console.log("Fetch Error :-S", err);
      });
  }
  startGame();
  $("#score").hide();
  startAnswers();
  function startAnswers() {
    $(optionA).on("click", function() {
      console.log("this is the correct button");
      console.log("this button is being clicked A");
      correct++;
      $("#correct").text(correct);
      $("#optionA").addClass("correct-button");
      $("#optionA").removeClass("correct-button");
      renderQuestion();
    });
    $(optionB).on("click", function() {
      console.log("wrong button");
      console.log("this button is being clicked B");
      incorrect++;
      $("#incorrect").text(incorrect);
      $("#optionB").addClass("incorrect-button");
      $("#optionB").removeClass("incorrect-button");
      renderQuestion();
    });
    $(optionC).on("click", function() {
      console.log("wrong button 2");
      console.log("this button is being clicked C");
      incorrect++;
      $("#incorrect").text(incorrect);
      $("#optionC").addClass("incorrect-button");
      $("#optionC").removeClass("incorrect-button");
      renderQuestion();
    });
    $(optionD).on("click", function() {
      console.log("wrong button 3");
      console.log("this button is being clicked D");
      incorrect++;
      $("#incorrect").text(incorrect);
      $("#optionD").addClass("incorrect-button");
      $("#optionD").removeClass("incorrect-button");
      renderQuestion();
    });
  }
})();
#container {
  text-align: center;
}

.game-wrapper {
  background: url(../images/background-copy.jpg);
  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  z-index: -1;
}

.card {
  background-color: rgb(0, 0, 0); /* Fallback color */
  background-color: rgba(0, 0, 0, 0.4); /* Black w/opacity/see-through */
  color: antiquewhite;
  padding: 150px;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.correct-button {
  background-color: green;
}

.incorrect-button {
  background-color: red;
}

#btnNext {
  background-color: black;
}

#score {
  background-color: rgb(0, 0, 0); /* Fallback color */
  background-color: rgba(0, 0, 0, 0.4); /* Black w/opacity/see-through */
  color: antiquewhite;
  padding: 150px;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link
      rel="stylesheet"
      href="//fonts.googleapis.com/css?family=Roboto:300,300italic,700,700italic"
    />

    <link
      rel="stylesheet"
      href="//cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.css"
    />

    <link
      rel="stylesheet"
      href="//cdnjs.cloudflare.com/ajax/libs/milligram/1.3.0/milligram.css"
    />
    <link rel="stylesheet" href="assets/css/style.css" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Trivia Game</title>
  </head>
  <body>
    <div class="game-wrapper"></div>
    <div id="container">
      <h1>Trivia Game</h1>
      <div class="card">
        <div id="question"></div>
        <div id="answers">
          <button id="optionA"></button>
          <button id="optionB"></button>
          <button id="optionC"></button>
          <button id="optionD"></button>
        </div>

        <button id="btnNext">NEXT QUESTION</button>
      </div>
    </div>
    <div id="score">
      <h1>END RESULTS</h1>
      <p>Correct: <span id="correct">0</span></p>
      <p>Incorrect: <span id="incorrect">0</span></p>
      <p>Unanswered: <span id="unanswered">0</span></p>
    </div>
    <script
      src="https://code.jquery.com/jquery-3.4.1.min.js"
      integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
      crossorigin="anonymous"
    ></script>
    <script src="assets/javascript/app.js"></script>
  </body>
</html>

1 Ответ

3 голосов
/ 14 октября 2019

В начале вашего файла сценария Java у вас было

  let optionA = $("#optionA");
  let optionB = $("#optionA");
  let optionC = $("#optionA");
  let optionD = $("#optionA");

Я изменил их на

  let optionA = $("#optionA");
  let optionB = $("#optionB");
  let optionC = $("#optionC");
  let optionD = $("#optionD");

, и это решило вашу проблему !! иногда это глупые мелочи, которые тебя достают.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...