在我的.JS文件中时,jQuery“ $”得到“ ReferenceError:$未定义”

时间:2019-12-01 15:18:39

标签: javascript jquery html

当我用HTML编写JS时,我的代码可以正常工作:

<!DOCTYPE html>

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <title>Address Book</title>
</head>
<body>
<input id="submitButton" type = "submit" value = "Save">
<script>
    $("#submitButton").on("click", function() {
    console.log("result!");
});
</script>
</body>

但是当我将其拆分成自己的.js文件时,JS文件无法识别JQuery'$'符号。这是当前在HTML和JS中的外观(我将.JS源添加到HTML文件中):

<!DOCTYPE html>

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    **<script type="text/javascript" src="addressBook.js"></script>**
    <title>Address Book</title>
</head>
<body>
<input id="submitButton" type = "submit" value = "Save">
</body>

并在addressBook.js文件中:

$("#submitButton").on("click", function() {
    console.log("omg, you clicked me!");

单击按钮时,我将以下错误记录到控制台:

  

$(“#submitButton”)。on(“ click”,function(){   ^   ReferenceError:未定义$

任何帮助将不胜感激!

谢谢

3 个答案:

答案 0 :(得分:2)

Wat selfagency说,+将脚本标签放在正文的末尾。

html文件

<!DOCTYPE html>

<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <title>Address Book</title>
  </head>
  <body>
    <input id="submitButton" type="submit" value="Save" />
    <script type="text/javascript" src="addressBook.js"></script>
  </body>
</html>

addressbook.js

$('#submitButton').on('click', function() {
  console.log('result!');
});

在这种情况下,头部中的script标签不起作用的原因是因为运行addressBook脚本时该按钮在DOM中尚不存在。详细介绍here

答案 1 :(得分:0)

我认为您不需要在正文结尾之前添加脚本。 创建了addressBook.js并更改了jquery

之后,

$('#submitButton').on('click', function() {
 console.log("omg, you clicked me!");
});
<!DOCTYPE html>
  
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
      <script type="text/javascript" src="addressBook.js"></script>
    <title>Address Book</title>
  </head>
  <body>
    <input id="submitButton" type="submit" value="Save" />

  </body>
</html>

答案 2 :(得分:-1)

<script>
    $("#submitButton").on("click", function() {
console.log("result!");
</script>

那是不正确的语法。应该是:

<script>
$(document).ready(function () {
  $("#submitButton").on("click", function() {
    console.log("result!");
  });
});
</script>