我們旺旺需要調(diào)用別的 js文件。怎么處理?
看隨機(jī)抽取這個(gè)例子。在一個(gè)頁(yè)面中如下:
<html> <head> <title>random number</title> <script type="text/javascript"> //隨機(jī)抽取人名 </script> </head> <body> <form> <input type="button" style='font-size:40px' value="Start" onclick="start()"> <input type="button" style='font-size:40px' value="Stop" onclick="stop();"> </form> <br> <font color="blue" style='font-size:150px' id="num"></font> <br> </body> </html>
我們可以把 js 放在另外一個(gè)文件里,比如當(dāng)前文件夾的 a.js 中。
這樣 html 頁(yè)面如下:
<html> <head> <title>random number</title> <script type="text/javascript" src="a.js"> </script> </head> <body> <form> <input type="button" style='font-size:40px' value="Start" onclick="start()"> <input type="button" style='font-size:40px' value="Stop" onclick="stop();"> </form> <br> <font color="blue" style='font-size:150px' id="num"></font> <br> </body> </html>
a.js
var errorString = "Please input a positive integer."; var arr = ["A", "B", "C", "D"]; function count() { max = arr.length; //max, 全局變量 document.getElementById("num").innerHTML = arr[parseInt(max * Math.random())]; } function start() { timeId = setInterval("count();", 100); } function stop() { clearInterval(timeId); }
這樣就行了。
當(dāng)然,也可以把 a.js放在web上,然后引用成下面這樣。
<html> <head> <title>random number</title> <script type="text/javascript" src="http://localhost:8080/test/js/random1.js"></script> </head> <body> <form> <input type="button" style='font-size:40px' value="Start" onclick="start()"> <input type="button" style='font-size:40px' value="Stop" onclick="stop();"> </form> <br> <font color="blue" style='font-size:150px' id="num"></font> <br> </body> </html>
路徑的寫(xiě)法是很有講究的,例如:目標(biāo)文件login.js是在項(xiàng)目根目錄下的一個(gè)叫JS的文件夾下,
1.若母文件在根目錄下,則應(yīng)這樣寫(xiě):
<script type="text/javascript" src="JS/login.js"></script>
這個(gè)時(shí)候下面的兩種寫(xiě)法是不正確的:
<script type="text/javascript" src="/JS/login.js"></script>
<script type="text/javascript" src="../JS/login.js"></script>
2.若母文件在根目錄下的一個(gè)叫l(wèi)ogin的文件夾下,則應(yīng)這樣寫(xiě):
<script type="text/javascript" src="../JS/login.js"></script>
這個(gè)時(shí)候下面的兩種寫(xiě)法是不正確的:
<script type="text/javascript" src="/JS/login.js"></script>
<script type="text/javascript" src="JS/login.js"></script>
同樣對(duì)CSS文件的引用也是這樣的。
以上所述是小編給大家介紹的引入(調(diào)用)一個(gè)JS文件的方法,希望對(duì)大家有所幫助
如對(duì)本文有疑問(wèn),請(qǐng)?zhí)峤坏浇涣髡搲?,廣大熱心網(wǎng)友會(huì)為你解答!! 點(diǎn)擊進(jìn)入論壇