外部Js文件无法运行Jquery

External Js file cannot run Jquery

本文关键字:运行 Jquery Js 文件 外部      更新时间:2023-09-26

我的外部js文件(example.js):

alert("External js file has just been loaded !");
$("#start").click(function (e) {
    alert("Starting !");  
});

我的HTML文件有<script type="text/javascript" src="example.js"></script>。当我加载页面时,它会提醒"External js file has just been loaded !",这意味着js文件已成功加载。

但是,当我单击"开始"按钮时,它不会提醒"Starting !"

当我在html文件中插入example.js文件的内容时,它可以提醒"Starting !":

<script>
    alert("External js file has just been loaded !");
    $("#start").click(function (e) {
        alert("Starting !");  
    });
</script>

如何修复外部js文件的此类问题?

确保在example.js之前注入了jquery脚本。

例如:

<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="example.js"></script>

如果您遇到任何错误,请检查您的控制台。

尝试使用$.getScript().ready()加载"example.js"

$(function() {
  $.getScript("example.js")
})

我刚刚尝试过,一切似乎都很好。

$(document).ready(function() {
  $("#world-button").click(function() {
    alert("Hello World");
  });
});
<!DOCTYPE HTML>
<html>
<head>
  <meta charset="utf-8">
  <title>Demo</title>
</head>
<body>
  <button id="world-button">Hello World</button>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</body>
</html>

之所以发生这种情况,是因为您尚未在document.ready函数中写入click事件。事件应该在DOM准备就绪时编写。

$(document).ready(function(){
  $("#start").click(function (e) {
    alert("Starting !");  
  });
});

您可以在此处找到更多详细信息:https://learn.jquery.com/using-jquery-core/document-ready/