<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title> 事件 演示 </title>
<style>
div {
border: 1px solid #ccc;
margin: 10px 0;
padding: 0 10px;
}
</style>
</head>
<body>
<button id="btn1"> 一个按钮 </button>
<div id="div1">
<p id="p1"> 激活 </p>
<p id="p2"> 勾销 </p>
<p id="p3"> 勾销 </p>
<p id="p4"> 勾销 </p>
</div>
<div id="div2">
<p id="p5"> 勾销 </p>
<p id="p6"> 勾销 </p>
</div>
<div id="div3">
<a href="#">a1</a><br>
<a href="#">a2</a><br>
<a href="#">a3</a><br>
<a href="#">a4</a><br>
<button> 加载更多...</button>
</div>
<script src="./event.js"></script>
</body>
</html>
// 一般绑定
const btn1 = document.getElementById('btn1')
bindEvent(btn1, 'click', function (event) {// console.log(event.target) // 获取触发的元素
event.preventDefault() // 阻止默认行为
alert(this.innerHTML)
})
// 代理绑定
const div3 = document.getElementById('div3')
bindEvent(div3, 'click', 'a', function (event) {event.preventDefault()
alert(this.innerHTML)
})
- 基于 DOM 树形构造
- 事件会顺着触发元素往上冒泡
- 利用场景:事件代理
const p1 = document.getElementById('p1')
bindEvent(p1, 'click', event => {event.stopPropagation() // 阻止冒泡
console.log('激活')
})
const body = document.body
bindEvent(body, 'click', event => {console.log('勾销')
// console.log(event.target)
})
const div2 = document.getElementById('div2')
bindEvent(div2, 'click', event => {console.log('div2 clicked')
console.log(event.target)
})
- 事件代理
- 用 e.target 获取触发元素
- 用 matches 来判断是否是触发元素