事件委托
事件冒泡机制:父元素帮子元素处理事件。
使用场景:动态新增元素。
难点:需要利用事件的target过滤当事元素在操作
<!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>冒泡机制</title>
<style>
#red {
width: 600px;
height: 600px;
background-color: red;
}
#green {
width: 400px;
height: 400px;
background-color: green;
}
#blue {
width: 200px;
height: 200px;
background-color: blue;
}
</style>
</head>
<body>
<div id="red">
<div id="green">
<div id="blue"></div>
</div>
</div>
<script>
red.onclick = function (e) {
console.log('red被点击:',red);
//target属性
console.log('e',e);
console.log(e.target);
}
green.onclick = function () {
console.log('green被点击:',green);
}
blue.onclick = function (e) {
//停止传播
e.stopPropagation()
console.log('blue被点击:',blue);
}
</script>
</body>
</html>
而在jQuery提供on方法,为委托而生
.0n(‘参数1’,‘参数2’,‘参数3’)
参数1:事件名
参数2:选择器,用于过滤处理子元素的事件
参数3:函数中的this指向当事元素,代替target方案
<!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>事件委托</title>
<style>
#box {
padding: 20px;
background-color: #aaa;
display: flex;
}
#box > div {
width: 100px;
height: 100px;
background-color: red;
margin: 10px;
}
</style>
</head>
<body>
<div id="box">
<div></div>
<div></div>
<div></div>
</div>
<script src="../vendor/jquery-3.6.0.js"></script>
<script>
// '>div' 表示选择器——'#box>div'
$('#box').on('click', '>div', function () {
console.log(this)
$(this).css('border', '2px solid orange')
})
</script>
</body>
</html>