事件绑定
var btn = document.getElementById('submit')
btn.addEventListener('click',event=>{
console.log('点击按钮')
})
//通用事件绑定
function bindEvent(el,type,fn){
el.addEventListener(type,fn)
}
const btn = document.getElementById('btn')
bindEvent(btn'click',e=>{
e.preventDefault()
console.log(e.target)
})
事件冒泡
<body>
<div id='div1'>
<p id='p1'>激活</p>
<p id='p2'>取消</p>
<p id='p2'>取消</p>
</div>
</body>
const p1 = document.getElementById('p1')
const body = document.body
bindEvent(p1,'click',e=>{
//e.stopPropagation() //阻止事件冒泡
console.log('激活')
})
bindEvent(body,'click',e=>{
console.log('body click')
console.log(e.target) //因为冒泡机制,点击p或div标签都会触发body的click事件
})
事件代理
const box= document.getElementById('box')
bindEvent(box,'click',event=>{
event.preventDefault()
const target = event.target
if(target.nodename==='a'){
alert(target.innerHTML)
}
}
)