外部Js文件不能运行Jquery
External Js file cannot run Jquery
我的外部 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 !"
。
当我将example.js文件的内容插入html文件时,它可以提示"Starting !"
:
<script>
alert("External js file has just been loaded !");
$("#start").click(function (e) {
alert("Starting !");
});
</script>
如何解决外部 js 文件的问题?
这是因为您没有在 document.ready 函数中编写点击事件。应该在 DOM 就绪时写入事件。
$(document).ready(function(){
$("#start").click(function (e) {
alert("Starting !");
});
});
您可以在此处找到更多详细信息:https://learn.jquery.com/using-jquery-core/document-ready/
尝试使用 $.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>
确保在 example.js
.
之前注入了 jquery
脚本
例如:
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="example.js"></script>
如果出现任何错误,请检查您的控制台。
我的外部 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 !"
。
当我将example.js文件的内容插入html文件时,它可以提示"Starting !"
:
<script>
alert("External js file has just been loaded !");
$("#start").click(function (e) {
alert("Starting !");
});
</script>
如何解决外部 js 文件的问题?
这是因为您没有在 document.ready 函数中编写点击事件。应该在 DOM 就绪时写入事件。
$(document).ready(function(){
$("#start").click(function (e) {
alert("Starting !");
});
});
您可以在此处找到更多详细信息:https://learn.jquery.com/using-jquery-core/document-ready/
尝试使用 $.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>
确保在 example.js
.
jquery
脚本
例如:
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="example.js"></script>
如果出现任何错误,请检查您的控制台。