事件捕获、冒泡&事件委托
- 1、事件捕获与冒泡
- 2、事件冒泡示例
- 3、阻止事件冒泡
- 4、阻止事件默认行为
- 5、事件委托
- 6、事件委托优点
1、事件捕获与冒泡
2、事件冒泡示例
<!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>
.parent {
width: 300px;
height: 200px;
border: 1px solid #ccc;
background: #f5f5f5;
}
.son {
width: 100px;
height: 100px;
background: pink;
text-align: center;
line-height: 90px;
}
</style>
</head>
<body>
<div class="parent">
<div class="son">son</div>
</div>
</body>
<script>
const son = document.getElementsByClassName('son')[0];
const parent = document.getElementsByClassName('parent')[0];
son.onclick = function (e) {
console.log('son click');
};
parent.onclick = function (e) {
console.log('parent click');
};
</script>
</html>
当在页面触发 son 元素的点击事件时,因为事件冒泡,会依次打印 son click、parent click。
3、阻止事件冒泡
const son = document.getElementsByClassName('son')[0];
const parent = document.getElementsByClassName('parent')[0];
son.onclick = function (e) {
console.log('son click');
e.stopPropagation(); // 阻止事件冒泡
};
parent.onclick = function (e) {
console.log('parent click');
};
当在页面触发 son 元素的点击事件时,只会打印 son click。
4、阻止事件默认行为
💡 Tips:e.preventDefault() 或 return false 会阻止默认行为
<!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>
<a href="http://www.baidu.com">百度</a>
</body>
<script>
const aDom = document.getElementsByTagName('a')[0];
aDom.onclick = function (e) {
console.log('a click');
e.preventDefault(); // 阻止默认跳转
// return false; // 阻止默认跳转
};
</script>
</html>
5、事件委托
<!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>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</body>
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<script>
// 将 li 的点击事件注册到 ul 上
$('ul').on('click', 'li', function () {
console.log(this); // <li>x</li>
});
</script>
</html>