javaScript的引入方式

來源:互聯網
上載者:User

今天下午複習JavaScript的一開始,就遇到一個問題:JavaScript的三種引入方式是什麼。 

我對這個問題一直是迷迷糊糊的,大概知道用<script>標籤和src屬性,但是不是很明確。因此上網去查了一下資料,發現答案有好幾個版本,有寫三個的,兩個的,還有四個的,所以為瞭解決這個問題,我決定逐一嘗試。

1)直接在HTML頁面中使用<script></script>標籤引入,可以寫在head中,也可以寫在body末尾,可以實現

<!doctype html><html lang="en"> <head>  <meta charset="UTF-8">  <meta name="Generator" content="EditPlus®">  <meta name="Author" content="">  <meta name="Keywords" content="">  <meta name="Description" content="">  <title>js引入方式實驗</title> </head> <body>        js的引入方式實驗<button id="button">實驗</button>        <script>            button.onclick=function(){alert("引入方法一:直接嵌入script標籤");}        </script> </body></html>
效果如下圖所示:點擊按鈕會彈出提示框



2).在html中使用script的src屬性引入外部js檔案,可實現。

建立一個index1.html和index1.js檔案,代碼如下:

<!doctype html><html lang="en"> <head>  <meta charset="UTF-8">  <meta name="Generator" content="EditPlus®">  <meta name="Author" content="">  <meta name="Keywords" content="">  <meta name="Description" content="">  <title>js引入方式實驗</title> </head> <body>        js的引入方式實驗<button id="button">實驗</button>        <script src="index1.js">           </script> </body></html>
index1.js原始碼如下: 

button.onclick=function(){alert("JS引入方式2:外部檔案匯入");}

效果如下圖所示:


3).事件定義,直接在組件後面的事件中寫javascript:js代碼,可實現

<!doctype html><html lang="en"> <head>  <meta charset="UTF-8">  <meta name="Generator" content="EditPlus®">  <meta name="Author" content="">  <meta name="Keywords" content="">  <meta name="Description" content="">  <title>js引入方式實驗</title> </head> <body>        js的引入方式實驗<button id="button" onclick="javascript:alert('js引入的方式3:事件定義')">實驗</button> </body></html>
效果圖如下所示:


4).在一個js檔案中調用另外一個js 檔案,可實現。但不能直接在第一個js檔案中寫<script src=xx.js></script>,這樣寫會導致引入js檔案失敗

HTML檔案中引入index1-1.js

<!doctype html><html lang="en"> <head>  <meta charset="UTF-8">  <meta name="Generator" content="EditPlus®">  <meta name="Author" content="">  <meta name="Keywords" content="">  <meta name="Description" content="">  <title>js引入方式實驗</title> </head> <body>        js的引入方式實驗<button id="button">實驗</button><script src="index1-1.js"></script> </body></html>

index1-1.js原始碼

document.write("<script src='index1.js'></script>");
index1.js原始碼
button.onclick=function(){alert("JS引入方式2:外部檔案匯入");}
效果如下圖所示:







相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.