事件委托:就是将事件绑定在上一级,通过冒泡触发。
举个例子:页面上有这么一个节点树,ul>li>a;比如给最里面的a加一个click点击事件,那么这个事件就会一层一层的往外执行,执行顺序a>li>ul,有这样一个机制,那么我们给最外面的ul加点击事件,那么里面的li,a做点击事件的时候,都会冒泡到最外层的ul上,所以都会触发,这就是事件委托,委托它们父级代为执行事件。
捕获阶段:从window对象传导到目标节点(上层传到底层)称为“捕获阶段”(capture phase),捕获阶段不会响应任何事件;
目标阶段:在目标节点上触发,称为“目标阶段”
冒泡阶段:从目标节点传导回window对象(从底层传回上层),称为“冒泡阶段”(bubbling phase)。事件代理即是利用事件冒泡的机制把里层所需要响应的事件绑定到外层;
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#father {
width: 200px;
height: 200px;
background-color: red;
display: flex;
justify-content: center;
align-items: center;
}
#son {
width: 100px;
height: 100px;
background-color: aqua;
display: flex;
justify-content: center;
align-items: center;
}
#grandson {
width: 50px;
height: 50px;
background-color: rgb(243, 102, 144);
}
</style>
</head>
<body>
<div id="father">
<div id="son">
<div id="grandson">
</div>
</div>
</div>
<script>
let father = document.getElementById('father');
let son = document.getElementById('son');
let grandson = document.getElementById('grandson');
father.onclick = () => {
console.log("click father");
}
son.onclick = (e) => {
console.log("click son");
console.log("e.target", e.target);
}
grandson.onclick = () => {
console.log("click grandson");
}
</script>
</body>
</html>
关系图:
运行截图:
Demo:
动态实现列表的增加与删除
附答案:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text">
<button>添加</button>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<script>
let oUl = document.querySelector("ul");
let oIpt = document.querySelector('input');
let oBtn = document.querySelector('button');
let text = "";
let _this;
oIpt.oninput = function () {
// 注意使用箭头函数会导致this指向window
// console.log('this', this);
text = this.value;
_this = this;
}
oBtn.onclick = () => {
let newLi = document.createElement("li");
newLi.innerText = text;
oUl.appendChild(newLi);
_this.value = "";
}
oUl.onclick = (e) => {
// console.log('e.target', e.target);
oUl.removeChild(e.target);
}
</script>
</body>
</html>