1.事件绑定
<button id="btn">测试</button><script>
var btn = document.getElementById("btn")
btn.addEventListener("click", event => {
alert(event.target)
})</script>`
2.事件冒泡
<body>
<div id="div1">
<p>这是p1</p>
<p>这是p2</p>
<p>这是p3</p>
<p>这是p4</p>
</div>
</body>
<script>
let body=document.body;
body.addEventListener("click",event=>{
console.log("body click");
console.log(event.target);
})
let div1=document.getElementById("div1");
div1.addEventListener("click",event=>{
event.stopPropagation()//阻止冒泡;
console.log("div1 click")
console.log(event.target)//获取触发的元素
})
</script>
3.事件代理
function bindEvent(el, type, selector, fn) {
if (fn == null) {
fn = selector;
selector = null;
}
el.addEventListener(type, event => {
let target
if (selector) { //事件代理
target = event.target;
if (target.matches(selector)) {
fn.call(target, e)
}
} else {//不需要代理
fn(e)
}
});
}
来源:CSDN
作者:45度阳光
链接:https://blog.csdn.net/weixin_43811701/article/details/104355719