<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>...</title>
<script>
</script>
</head>
<body>
<button id="btnShoot">shoot</button><br>
<button id="btnAward">获得跟踪导弹</button><br>
<button id="btnBreak">失去跟踪导弹</button><br>
</body>
<script>
//1、查找触发事件元素
var btnShoot=document.getElementById("btnShoot");
var btnAward=document.getElementById("btnAward");
var btnBreak=document.getElementById("btnBreak");
//2、添加事件监听对象
//当单击发射按钮时,暂时只能发射一种普通子弹
btnShoot.addEventListener("click",function(){
console.log("发射普通子弹。。。");
});
//定义发射导弹的函数。注意:这里不能用匿名函数,为后面的移除函数准备
function shoot2(){
alert("发射跟踪导弹=> => =>");
}
//单击 btnAward获得奖励按钮时,不是发射子弹,而是给btnShoot再多绑定一种新的子弹
btnAward.onclick=function(){
btnShoot.addEventListener("click",shoot2);
}
//绑定后,再单击btnShoot,就可以同时发射两种子弹
//单击损毁按钮,从btnShoot上移除导弹
btnBreak.onclick=function(){
btnShoot.removeEventListener("click",shoot2);
}
//此时,再单击btnShoot按钮,就只能发射一种子弹了
</script>
</html>
(day05—03)在js中通过添加事件监听对象
猜你喜欢
转载自blog.csdn.net/qq_43459224/article/details/90083346
今日推荐
周排行