简体   繁体   English

jQuery在外部js文件中不起作用

[英]jQuery doesn't work in an external js file

I'm a beginner of jQuery. 我是jQuery的初学者。 I wanne write my jQuery in an external js file instead of in the head of html file, but it failed. 我想用外部js文件而不是html文件的头来编写jQuery,但是失败了。

index.html: index.html:

<!DOCTYPE html>
<head>
<script src="js/func.js"></script>
</head>
<body>
<p id="response">response is shown here</p>
<button id="bt_testJQ">jq test</button>
</body>
</html>

func.js func.js

document.write("<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js'></script>")`
`$(document).ready(function () {
    $("#bt_testJQ").click(function () {
        $("#response").toggle();
    })
})

` `

This has nothing to do with putting the code in an external file, you'd have the same problem if it was inline. 这与将代码放入外部文件无关,如果代码是内联的,则会遇到相同的问题。

document.write 's output is placed after the <script></script> element and parsed by the HTML parser when the script has finished running. document.write的输出放置在<script></script>元素之后,并在脚本完成运行后由HTML解析器进行解析。 Effectively, you are: 实际上,您是:

  1. setting up jQuery to load 设置要加载的jQuery
  2. Trying to use jQuery 尝试使用jQuery
  3. actually loading jQuery 实际加载jQuery

You can't use jQuery before you load it. 加载前不能使用jQuery。

The simple solution to this is to use two script elements in the HTML and load jQuery first. 一个简单的解决方案是在HTML中使用两个脚本元素并首先加载jQuery。

<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js'></script>
<script src="js/func.js"></script><!-- with the document.write line removed -->

just wanna to avoid importing the jquery in every html file. 只是想避免在每个html文件中导入jquery。

This is best handled by either: 最好由以下任一方法处理:

  • Using a template system. 使用模板系统。
  • Using a build system that combines the contents of all your scripts, including third party libraries, into a single file. 使用将所有脚本(包括第三方库)的内容组合到一个文件中的构建系统。

A better way of doing this is have the jquery library called at the head and have your external js script at the last part of the body of your html 更好的方法是在顶部调用jquery库,并在html主体的最后部分使用外部js脚本

html code HTML代码

<!DOCTYPE html>
<head>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js'></script>
</head>
<body>
<p id="response">response is shown here</p>
<button id="bt_testJQ">jq test</button>
<script src="js/func.js"></script>
</body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM