2015-10-13 41 views
0

我是jQuery的初學者。我想寫我的jQuery在外部的js文件而不是在html文件的頭部,但它失敗了。jQuery無法在外部js文件中工作

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

`

+0

把這部分'document.write'放在文檔裏面準備好嗎?或者把你的外部腳本放在body當元素加載時 – guradio

+1

這個問題是爲什麼你會這樣做?只需在func.js之前將它包含在

-1

這樣做的更好的方法是有一個叫jQuery庫在頭上d將您的HTML

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> 
+0

thx!有用。你能給我一個簡短的解釋嗎? – Lynn

+0

似乎「document.write」不會在func.js中導入jquery庫。 jquery lib必須在index.html中導入。 – Lynn

+0

@Lynn從我還了解到,在添加事件處理程序功能之前,您必須首先獲取DOM元素。看起來您的原始代碼正試圖運行腳本1st,但它將執行的元素尚不存在。 – Dren

相關問題