JavaScript:绑定事件

执行以下代码,点击按钮,只会弹出第二个函数的‘b’。那么,现在要两个都弹出,就需要事件绑定。

<!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>

绑定事件使用addEventListener( 事件名,函数,false )。如下,绑定两个事件之后,点击一次按钮,都可以弹出。但是addEventListener的兼容性不好,在IE下使用attachEvent。

<!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>

 

posted @ 2020-02-25 19:59  昨夜昙花  阅读(7)  评论(0)    收藏  举报