1.通用的事件绑定函数
function bindEvent(elem,type,fn){
elem.addEventListener(type,fn);
}
const btn1=document.getElementById('btn1');
bindEvent(btn1,'click',event=>{
//console.log(event.target);
//console.log(event.preventDefault());
alert('Hello');
})
2.事件冒泡
解释:比如有大小两个div,其中大的div嵌套小的div,如果点击小的div,不仅会触发小的div的click事件,同时也会触发大的div的click事件
const p1=document.getElementById('p1');
bindEvent(p1,'click',e=>{
e.stopPropgation();//阻止事件冒泡
alert('激活');
});
bindEvent(body,'click',e=>{
alert('取消');
});
3.事件代理
解释:如果元素太多,不方便一一绑定事件,我们可以将事件绑定在元素的父元素上面,简化代码
const div3=document.getElementById('div3');
bindEvent(div3,'click',event=>{
event.preventDefault();
const target=event.target;
if(target.Name==='A'){
alert(target.innerHtml);
}
});