【概念簡介】在HTML中嵌入Javas cript指令碼,javascript
Javas cript 必需嵌入到 HTML 文檔,才能被瀏覽器解釋和執行。
將 Javas cript 指令碼嵌入到 HTML 文檔中有3種標準方法:
通過 <s cript> 標籤嵌入;
引入外部指令碼;
在 HTML 屬性中直接嵌入。
一. 通過<s cript>標籤嵌入
通過 <s cript> 標籤嵌入Javas cript代碼時,必需將代碼放在 <s cript type="text/javas cript"> 和 </s cript> 標記對之間。
【例1-2】通過<s cript>標籤嵌入Javas cript代碼:
|
1
2
3
4
5
6
7
8
9
10
11
12 |
<html>
<head>
<title>通過<s cript>標籤嵌入</title>
</head>
<bdoy>
<!-- 開始嵌入Javas cript代碼 -->
<s cript type="text/javas cript">
document.write("這是通過<s cript>標籤嵌入的代碼"); // 輸出語句
</s cript>
<!-- 結束 -->
</body>
</html> |
瀏覽器載入HTML文檔時,會識別 <s cript> 標籤,執行其中的 Javas cript 代碼,然後將結果返回並在瀏覽器視窗顯示。
二. 引入外部指令碼
當網頁功能比較複雜,或通用代碼(每個頁面都是用)較多時,直接在 <s cript> 標籤中嵌入 Javas cript 代碼會導致網頁雜亂,不易管理。這時候,我們希望能將Javas cript代碼儲存在單獨的檔案中,使用時再嵌入到 HTML 文檔。
可以通過 <s cript> 標籤的 src 屬性引入外部檔案。
例如,引入網站根目錄下的 demo.js 檔案:
|
1 |
<s cript type="text/javas cript" src="/demo.js"></s cript> |
引入上級目錄中 s cript 目錄下的 demo.js 檔案:
|
1 |
<s cript type="text/javas cript" src="../s cript/demo.js"></s cript> |
引入百度的 Javas cript 檔案:
|
1 |
<s cript type="text/javas cript" src="http://www.baidu.com/s cript/demo.js"></s cript> |
【例1-3】引入外部指令碼:
|
1
2
3
4
5
6
7
8 |
<html>
<head>
<title>引入外部指令碼</title>
</head>
<bdoy>
<s cript type="text/javas cript" src="1-3.js"></s cript>
</body>
</html> |
將上面代碼儲存為 1-3.html ,並在同一目錄下建立一個 Javas cript 指令檔,命名為1-3.js,輸入如下代碼:
|
1 |
document.write("引入外部指令碼"); |
在瀏覽器中開啟 1-3.html ,顯示 ”引入外部指令碼“,外部指令碼成功引入並執行。
引入外部指令碼,能夠很輕鬆的讓多個頁面使用相同的 Javas cript 代碼。外部指令碼一般會被瀏覽器儲存在快取檔案中,使用者再次訪問網頁時,無需重新載入,加快了網頁開啟速度。
注意:外部指令碼一般儲存為 .js 的檔案。
三. 在 HTML 屬性中直接嵌入
在 HTML 屬性中嵌入 Javas cript 代碼主要是針對 Javas cript 事件。Javas cript 事件是指使用者對網頁進行操作時,網頁做出相應的響應。
【例1-4】按一下滑鼠事件:
|
1
2
3
4
5
6
7
8 |
<html>
<head>
<title>按一下滑鼠事件</title>
</head>
<bdoy>
<p onclick="alert('你已經點擊了我!');">請點擊這裡</p>
</body>
</html> |
【例1-4】滑鼠雙擊事件:
|
1
2
3
4
5
6
7
8 |
<html>
<head>
<title>滑鼠雙擊事件</title>
</head>
<bdoy>
<p ondblclick="alert('你已經雙擊了我!');">請雙擊這裡</p>
</body>
</html> |
【例1-5】滑鼠移入事件:
|
1
2
3
4
5
6
7
8 |
<html>
<head>
<title>滑鼠雙擊事件</title>
</head>
<bdoy>
<p onmouseover="alert('你的滑鼠已移動!');">請將滑鼠移動到這裡</p>
</body>
</html> |
說明:alert() 函數彈出一個警告框。
嵌入指令碼的位置
<s cript> 標籤嵌入的指令碼和外部引入的指令碼可以放在 <head> 標籤和 <body> 標籤的任意位置。
上面的幾個例子,都是將 Javas cript 代碼嵌入到 <body> 標籤,下面示範在 <head> 標籤中嵌入指令碼。
【例1-6】在 <head> 標籤中引入外部指令碼
|
1
2
3
4
5
6
7
8
9 |
<html>
<head>
<title>引入外部指令碼</title>
<s cript type="text/javas cript" src="1-3.js"></s cript>
</head>
<bdoy>
<p> 在<head>標籤中引入外部指令碼 </p>
</body>
</html> |
【例1-6】通過 <s cript> 標籤嵌入指令碼
|
1
2
3
4
5
6
7
8
9
10
11
12
13 |
<html>
<head>
<title>引入外部指令碼</title>
</head>
<bdoy>
<p id="demo">請點擊這裡</p>
<s cript type="text/javas cript">
document.getElementById("demo").onclick=function(){
alert("你已經點擊了我");
}
</s cript>
</body>
</html> |