跳到主要内容

事件代理(委托)是什么?

事件代理

  • 用 e.target 获取触发元素
  • 用 matches 来判断是否是触发元素

代码演示:

const p = document.getElementById('p')
const body = document.body
p.addEventListener('click', e => {
e.stopPropagation() // 注释后,就会事件冒泡
console.log(1)
})
body.addEventListener('click', e => {
const target = e.target
if(target.matches('p')){
console.log(2)
}
})