事件绑定
const btn = document.getElementById("btn")
btn.addEventListener('click',event=>{console.log('click')
})
通用的事件绑定函数
function bindEvent(elem,type,fun){elem.addEventListener(type,fun)
}
const btn1 = document.getElementById('btn1')
bindEvent(btn1,'click',event=>{console.log(event.target)// 获取触发的元素
event.preventDefault()// 阻止默认行为,比方 a 标签,点击之后会跳转页面,加了次属性之后,不会跳转页面
alert('click')
})
阻止冒泡行为
const body = document.body
bindEvent(body,'click',e=>{console.log('激活')
console.log(e.target)
})
const p1 = document.getElementById('p1')
bindEvent(p1,'click',e=>{e.stopPropagation()// 阻止冒泡
console.log('勾销')
console.log(e.target)
})
//const div2 = document.getElementById('div2')
//bindEvent(div2,'click',e=>{// console.log('div2 click')
// console.log(e.target)
//})