0

我一直在努力将所有这些联系起来。我的琐事游戏包含在一个函数中,并且按钮全部自行触发,但按顺序排列。

所以如果我点击A然后自己开火#optionB #optionC#optionD此外,我只能单击一个选项(#optionA)来呈现下一个问题。这是一个 JSFiddle 链接。但是,如果您要在 Visual Studio Code 等中运行该链接,则该链接无法正常工作,但是所有代码都在 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 it's 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>

4

1 回答 1

3

在你的 JavaScript 文件的开头,你有

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

我把它们改成

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

这解决了你的问题!有时是愚蠢的小事让你着迷。

于 2019-10-14T16:48:19.567 回答