1. 程式人生 > >js在HTML中的三種寫法

js在HTML中的三種寫法

set 定位 script 內容 jpg 添加 彈窗 引用 brush

1.內聯樣式

內聯樣式分為兩種,一是直接寫入元素的標簽內部

<html>
	<title>js樣式內聯寫法</title>
	<meta http-equiv="content-type" content="text/html; charset=utf-8" /> 
	<body>
	<!--js內聯寫法01開始-->
       <!--當鼠標點擊圖片時跳出彈窗顯示1223-->
		<div class="img">
		單擊事件:
			<img src="images/001.jpg" onclick="alert(1223)"></img>
		</div>
	<!--js內聯寫法01結束-->
	</body>
</html>

二是寫入到<script></script>標簽中

給元素添加id

通過getElementById(‘XX‘);方法定位到該元素,給該元素添加觸發事件

註意:<script></script>標簽應該放在</body>之後

<html>
	<title>js樣式內聯寫法</title>
	<meta http-equiv="content-type" content="text/html; charset=utf-8" /> 
	<body>
	<!--js內聯寫法02開始-->	
	<div class="img">
		單擊事件:
			<img src="images/002.jpg" id=‘yuansu‘></img>
	</div>
	<!--js內聯寫法02結束-->
	</body>
	<script>
		//js代碼
		//找到XX元素,一般給元素加id	
		yuansuojb=document.getElementById(‘yuansu‘);		
		//給xx元素加事件
		yuansuojb.onclick=function(){
			//代碼段
			alert(1);
		}
		//觸發事件
	</script>
</html>

2.外聯樣式

將js的代碼寫到.js的文件中,並在HTML中引用

.html文件內容如下:

<html>
	<title>js樣式外聯寫法</title>
	<meta http-equiv="content-type" content="text/html; charset=utf-8" /> 
	<body>
	<div class="img">
		外聯寫法--單擊事件:
			<img src="images/003.jpg" id=‘yuansu‘></img>
	</div>
	</body>
	<script src=‘js/index.js‘></script>
</html>

.js文件內容如下:

//js代碼
//找到XX元素,一般給元素加id	
yuansuojb=document.getElementById(‘yuansu‘);		
//給xx元素加事件
yuansuojb.onclick=function(){
	//代碼段
	var str="hello world !!!";
	alert(str);
}

js在HTML中的三種寫法