我在外部 js 文件中运行简单的 jQuery 脚本时遇到问题。
$("#main-nav").click(function(){
alert("hello");
});`
我在 jQuery 文件之后的 html 中声明了外部 js 文件。
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="externalfile.js"></script>`
加载页面时没有任何反应,并且控制台中没有出现任何错误。
最佳答案
猜测一下,因为这里没有足够的信息,但我相对确定你已经放置了这些 <script>
您的 <head>
中的标签,它们将在 DOM 准备好之前执行。由于 DOM 尚未准备好,因此您无法将单击事件绑定(bind)到它。将您的代码包装在 $(document).ready()
中:
$(documment).ready(function () {
$("#main-nav").click(function(){
alert("hello");
});
});
现在,绑定(bind)点击处理程序的代码将在 DOM 准备好并能够将事件绑定(bind)到它之后运行。
关于javascript - 外部 .js 文件中的 JQuery 未运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31835005/