【问题标题】:ReferenceError: $ is not defined although jQuery is properly initializedReferenceError: $ is not defined 尽管 jQuery 已正确初始化
【发布时间】:2021-03-11 13:16:48
【问题描述】:

我只是从 JS、jQuery 和 Node JS 开始,现在尝试在 localhost:3000 服务器上从 Hyper 运行我的 Simon Game。我的 JS 代码中的第一个 $ 符号出现引用错误,如下所示:

\Simon_Game\game2.js:18

$(document).keypress(function() { ^ ReferenceError: $ is not defined 在对象。 (C:\Users\dkhme\OneDrive\The Complete 2020 Web Development Bootcamp\Web Development\Simon_Game\game2.js:18:3) 在 Module._compile (internal/modules/cjs/loader.js:1063:30) 在 Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10) 在 Module.load (internal/modules/cjs/loader.js:928:32) 在 Function.Module._load (internal/modules/cjs/loader.js:769:14) 在 Function.executeUserEntryPoint [作为 runMain] (内部/模块/run_main.js:72:12)在 internal/main/run_main_module.js:17:47 [nodemon] 应用程序崩溃 - 等待 在开始之前进行文件更改...

在链接到我的外部 JS 代码之前,我已经在我的 HTML 中正确引用了 jQuery。以下是我的 HTML 和 JS 代码:

<!DOCTYPE html>
<html lang="en" dir="ltr">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

<head>
  <meta charset="utf-8">
  <title>Simon Game</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
  <link rel="stylesheet" href="styles.css">
  <link href="https://fonts.googleapis.com/css?family=Press+Start+2P" rel="stylesheet">
  <!-- <script src="jquery-3.5.1.min.js"></script> -->
</head>

<body>

  <h1 id="level-title">Press Any Key to Start</h1>
  <div class="container">
    <div class="row">

      <div type="button" id="green" class="bbtn green">

      </div>

      <div type="button" id="red" class="bbtn red">

      </div>
    </div>

    <div class="row">

      <div type="button" id="yellow" class="bbtn yellow">

      </div>
      <div type="button" id="blue" class="bbtn blue">

      </div>

    </div>

    <!-- Button trigger modal -->
    <button type="button" class="rules btn btn-light btn-lg btn-block" data-toggle="modal" data-target="#staticBackdrop">
      Rules / Правила
    </button>

    <!-- Modal -->
    <div class="modal fade" id="staticBackdrop" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="staticBackdropLabel">Rules of the Game / Правила игры</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <p>ENG</p>
            <p>On your screen there are four colored buttons, each producing a particular tone when pressed or activated by the game. A round in the game consists of the game lighting up one random button, after which you must reproduce a sequence of
              buttons by pressing on them. On each level the game flashes only one button - the last in the current sequence. You must start by correctly reproducing the entire sequence of the previous level plus the button flashed by the game at the
              start of the current level. The level number corresponds to the total number of buttons in the current sequence. With each new level, the number of buttons to be pressed increases by one.</p>
            <p>RUS</p>
            <p>Игра представляет собой экран с четырьмя большими разноцветными кнопками, издающими разные звуки. Задача игры — запомнить продемонстрированную игроку последовательность этих вспышек и звуков и впоследствии воспроизвести её в рамках
              «раунда» игры. Начать игру можно нажатием любой кнопки. В каждом раунде игра показывает одну кнопку, которая должна стать последней в текущем раунде. Сначала необходимо воспроизвести последовательность кнопок предыдущего раунда и
              закончить его кнопкой, показанной в начале текущего раунда. Номер раунда соответствует общему количеству кнопок в текущей последовательности. С каждым раундом количество кнопок увеличивается на одну.</p>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
          </div>
        </div>
      </div>
    </div>

  </div>

  <!-- <script src="/js/jquery.min.js"></script> -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>


  <!-- <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> -->
  <!-- <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script> -->
  <!-- <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.min.js" integrity="sha384-w1Q4orYjBQndcko6MimVbzY0tgp4pWB4lZ7lr30WKz0vr/aWKhXdBNmNb5D92v7s" crossorigin="anonymous"></script> -->

  <script src="game2.js" charset="utf-8"></script>

</body>

<footer>
  <h5>Created by Dennis Norrstrand. Helsinki, Finland 2020.</h5>
</footer>

</html>

game2.js:

const express = require("express");
  const https = require("https");
  const app = express();
  const bodyParser = require("body-parser");

  app.get("/", function(req, res) {
    res.sendFile(__dirname + "/index.html");
  })

  let buttonColours = ["red", "blue", "green", "yellow"];

  let gamePattern = [];
  let userClickedPattern = [];

  let started = false;
  let level = 0;

  $(document).keypress(function() {
    if (!started) {
      $("#level-title").text("Level " + level);
      nextSequence();
      started = true;
    }
  });

  $(".bbtn").click(function() {

    let userChosenColour = $(this).attr("id");
    userClickedPattern.push(userChosenColour);

    playSound(userChosenColour);
    animatePress(userChosenColour);

    checkAnswer(userClickedPattern.length - 1);
  });

  function checkAnswer(currentLevel) {

    if (gamePattern[currentLevel] === userClickedPattern[currentLevel]) {
      if (userClickedPattern.length === gamePattern.length) {
        setTimeout(function() {
          nextSequence();
        }, 1000);
      }
    } else {
      playSound("wrong");
      $("body").addClass("game-over");
      $("#level-title").text("Game Over, Press Any Key to Restart");

      setTimeout(function() {
        $("body").removeClass("game-over");
      }, 200);

      startOver();
    }
  }

  function nextSequence() {
    userClickedPattern = [];
    level++;
    $("#level-title").text("Level " + level);
    let randomNumber = Math.floor(Math.random() * 4);
    let randomChosenColour = buttonColours[randomNumber];
    gamePattern.push(randomChosenColour);

    $("#" + randomChosenColour).fadeIn(100).fadeOut(100).fadeIn(100);
    playSound(randomChosenColour);
  }

  function animatePress(currentColor) {
    $("#" + currentColor).addClass("pressed");
    setTimeout(function() {
      $("#" + currentColor).removeClass("pressed");
    }, 100);
  }

  function playSound(name) {
    let audio = new Audio("sounds/" + name + ".mp3");
    audio.play();
  }

  function startOver() {
    level = 0;
    gamePattern = [];
    started = false;
  }

  app.listen(process.env.PORT || 3000, function() {
    console.log("Server is running on port 3000.");
  });

为什么会出现此参考错误?谢谢大家。

【问题讨论】:

  • 需要的是 Node.js,你不能在那里加载 jQuery
  • 你把服务器端代码和客户端代码搞混了

标签: javascript jquery


【解决方案1】:

Jquery 未正确加载。删除 cmets 并将其添加到您正在使用的行上方 &lt;script src="game2.js" charset="utf-8"&gt;&lt;/script&gt;

   <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> 
   <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
   <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.min.js" integrity="sha384-w1Q4orYjBQndcko6MimVbzY0tgp4pWB4lZ7lr30WKz0vr/aWKhXdBNmNb5D92v7s" crossorigin="anonymous"></script> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-24
    • 2018-07-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-18
    • 2021-12-10
    • 2018-08-27
    • 2018-08-03
    相关资源
    最近更新 更多