BOM-event事件

添加事件监听

    <button id="btnShoot">shoot</button><br>
    <button id="btnAward">获得跟踪导弹</button><br>
    <button id="btnBreak">失去跟踪导弹</button><br>
<script>
	btnShoot.addEventListener("click",function(){//添加事件监听
		console.log("发射普通子弹...");
	});
	function shoot2(){
		alert("发射跟踪导弹=>=>=>");
	}
	btnAward.addEventListener("click",function(){
		btnShoot.addEventListener("click",shoot2)
	});
	 // 移除事件

      //移除时,需要获得原处理函数的地址 , 如果一个处理函数可能被移除,则绑定时不能用匿名函数,必须用有名的函数

	btnBreak.addEventListener("click",function(){
		btnShoot.removeEventListener("click",shoot2)
	});
</script>	

 移除事件时的错误写法:

   <button id="btnShoot">shoot</button><br>
    <button id="btnAward">获得跟踪导弹</button><br>
    <button id="btnBreak">失去跟踪导弹</button><br>
	<script>
		btnShoot.addEventListener("click",function(){
			console.log("发射普通子弹");
		})
		btnAward.addEventListener("click",function(){
			btnShoot.addEventListener("click",function(){
				alert("发射跟踪导弹...");
			})
		})
		//移除事件时的错误写法
		btnBreak.addEventListener("click",function(){
		btnShoot.removeEventListener("click",function(){
				alert("发射跟踪导弹...");
			});
	});
	</script>

  

原文地址:https://www.cnblogs.com/lan-cheng/p/8364894.html