JavaScript: binding events

Execute the following code, click the button, it will pop up a second function of the 'b'. So, now both pop-up, you need to bind the event.

<!DOCTYPE html>
<html>
<head>
	<title>绑定事件</title>
</head>
<script type="text/javascript">
window.onload = function(){
	var oBtn = document.getElementById('btn1');
	oBtn.onclick = function(){
		alert('a');
	}
	oBtn.onclick = function(){
		alert('b');
	}
}
</script>
<body>
<input id="btn1" type="button" value="提交">
</body>
</html>

Binding event using addEventListener (event name, function, false). As follows, after binding the two events, click a button, you can pop up. However, poor compatibility addEventListener used in attachEvent IE.

<!DOCTYPE html>
<html>
<head>
	<title>绑定事件</title>
</head>
<script type="text/javascript">
//绑定事件:addEventListener(事件名,函数,false)
window.onload = function(){
	var oBtn = document.getElementById('btn1');
	oBtn.addEventListener('click',function(){
		alert('a');
	},false);
	oBtn.addEventListener('click',function(){
		alert('b');
	},false);
	// oBtn.onclick = function(){
	// 	alert('a');
	// }
	// oBtn.onclick = function(){
	// 	alert('b');
	// }
}
</script>
<body>
	<input id="btn1" type="button" value="提交">
</body>
</html>

 

Published 126 original articles · won praise 7 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_36880027/article/details/104503153