<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
width: 300px;
height: 300px;
background-color: pink;
margin-top: 10px;
}
</style>
</head>
<body>
<button class="add">添加事件</button>
<button class="remove">删除事件</button>
<div class="box"></div>
<script>
var add = document.querySelector(".add");
var remove = document.querySelector(".remove");
var box = document.querySelector(".box");
// // 点击“添加事件”按钮 为box绑定点击事件
add.onclick = function() {
// box.onclick = fn1; // 传统
// 如果使用添加时间监听的方式绑定事件,后面要解绑,必须要使用有名称函数称为事件处理程序
box.addEventListener('click', fn1); // 监听
box.addEventListener('click', fn2); // 监听
}
// 点击“删除事件”按钮 为box解绑事件
remove.onclick = function() {
// box.onclick = null; //传统解绑
box.removeEventListener('click', fn1) // 监听解绑
}
function fn1() {
alert("我被点击了1111")
}
function fn2() {
alert("我被点击了2222")
}
</script>
</body>
</html>