jQuery不能在外部js文件中工作

时间:2015-10-13 09:42:43

标签: javascript jquery html ajax

我是jQuery的初学者。我想把我的jQuery写在外部的js文件而不是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

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();
    })
})

`

2 个答案:

答案 0 :(得分:1)

这与将代码放在外部文件中无关,如果它是内联的,你会遇到同样的问题。

document.write的输出位于<script></script>元素之后,并在脚本运行完毕后由HTML解析器解析。实际上,你是:

  1. 设置 jQuery加载
  2. 尝试使用jQuery
  3. 实际加载jQuery
  4. 在加载之前,您无法使用jQuery。

    对此的简单解决方案是在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 -->
    
      

    只是想避免在每个html文件中导入jquery。

    最好由以下两种方法处理:

    • 使用模板系统。
    • 使用将所有脚本(包括第三方库)的内容组合到一个文件中的构建系统。

答案 1 :(得分:0)

更好的方法是在头部调用jquery库,并在html主体的最后部分使用外部js脚本

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>
相关问题