簡體   English   中英

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

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

我是jQuery的初學者。 我想用外部js文件而不是html文件的頭來編寫jQuery,但是失敗了。

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

`

這與將代碼放入外部文件無關,如果代碼是內聯的,則會遇到相同的問題。

document.write的輸出放置在<script></script>元素之后,並在腳本完成運行后由HTML解析器進行解析。 實際上,您是:

  1. 設置要加載的jQuery
  2. 嘗試使用jQuery
  3. 實際加載jQuery

加載前不能使用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。

最好由以下任一方法處理:

  • 使用模板系統。
  • 使用將所有腳本(包括第三方庫)的內容組合到一個文件中的構建系統。

更好的方法是在頂部調用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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM