js在HTML的三種引用方式詳解
1.內(nèi)聯(lián)樣式
內(nèi)聯(lián)樣式分為兩種,一是直接寫入元素的標(biāo)簽內(nèi)部
<html> <title>js樣式內(nèi)聯(lián)寫法</title> <meta http-equiv='content-type' content='text/html; charset=utf-8' /> <body> <!--js內(nèi)聯(lián)寫法01開始--> <!--當(dāng)鼠標(biāo)點擊圖片時跳出彈窗顯示1223--> <div class='img'> 單擊事件: <img src='http://m.cgvv.com.cn/bcjs/images/001.jpg' onclick='alert(1223)'></img> </div> <!--js內(nèi)聯(lián)寫法01結(jié)束--> </body></html>
二是寫入到<script></script>標(biāo)簽中
給元素添加id
通過getElementById(’XX’);方法定位到該元素,給該元素添加觸發(fā)事件
注意:<script></script>標(biāo)簽應(yīng)該放在</body>之后
<html> <title>js樣式內(nèi)聯(lián)寫法</title> <meta http-equiv='content-type' content='text/html; charset=utf-8' /> <body> <!--js內(nèi)聯(lián)寫法02開始--> <div class='img'> 單擊事件: <img src='http://m.cgvv.com.cn/bcjs/images/002.jpg' id=’yuansu’></img> </div> <!--js內(nèi)聯(lián)寫法02結(jié)束--> </body> <script> //js代碼 //找到XX元素,一般給元素加id yuansuojb=document.getElementById(’yuansu’);//給xx元素加事件 yuansuojb.onclick=function(){ //代碼段 alert(1); } //觸發(fā)事件 </script></html>
2.外聯(lián)樣式
將js的代碼寫到.js的文件中,并在HTML中引用
.html文件內(nèi)容如下:
<html> <title>js樣式外聯(lián)寫法</title> <meta http-equiv='content-type' content='text/html; charset=utf-8' /> <body> <div class='img'> 外聯(lián)寫法--單擊事件: <img src='http://m.cgvv.com.cn/bcjs/images/003.jpg' id=’yuansu’></img> </div> </body> <script src=’js/index.js’></script></html>
.js文件內(nèi)容如下:
//js代碼//找到XX元素,一般給元素加id yuansuojb=document.getElementById(’yuansu’); //給xx元素加事件yuansuojb.onclick=function(){ //代碼段 var str='hello world !!!'; alert(str);}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
