背景
承接上一篇理论部分,现在我要对理论进行验证,只有动手试验过才能真正理解。
parent.addEventListener('click', function(e) {
console.log("parent");
});
child.addEventListener('click', function(e) {
console.log("child");
});
grandchild.addEventListener('click', function(e) {
console.log("grandchild");
});
所有测试都是点击grand-child
case1:由内到外正常冒泡执行
case2 改变顺序先parent,不影响传播
parent.addEventListener('click', function(e) {
console.log("parent");
},true);
case3 阻断冒泡
parent.addEventListener('click', function(e) {
console.log("parent");
},true);
child.addEventListener('click', function(e) {
console.log("child");
});
grandchild.addEventListener('click', function(e) {
console.log("grandchild");
e.stopPropagation();
});
parent在capture就执行了,随后event传播给child和grandchilid。但是grandchild 调用了stopPropagation,阻断了传播过程。
case4 先capture并阻断传播
parent.addEventListener('click', function(e) {
console.log("parent");
e.stopPropagation();
},true);
child.addEventListener('click', function(e) {
console.log("child");
});
grandchild.addEventListener('click', function(e) {
console.log("grandchild");
});
这里parent通过设置capture:true先执行了,然后调用stop阻断了事件继续传播。所以只打印了console
结论
测试结果验证了我上一篇博客纯理论推测的内容,说明我的理解是正确的。这个知识可以帮助我在工作中控制事件流动,非常有用。
测试代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<style>
#parent {
background-color: red;
width: 250px;
height: 220px;
}
#child {
background-color: yellow;
height: 120px;
width: 120px;
margin: 0 auto;
}
#grand-child {
background-color: blue;
height: 50px;
width: 50px;
margin: 0 auto;
}
#msg,
#jQmsg,
#arrmsg {
font-size: 16px;
font-weight: 600;
background-color: #eee;
font-family: sans-serif;
color: navy;
}
</style>
</head>
<body>
<div id="parent">Parent-(attached event handler)<br><br>
<div id="child"> Child<br><br>
<p id="grand-child">Grand Child</p>
</div>
</div>
<div id="msg"></div><br>
<div id="jQmsg"></div><br>
<div id="arrmsg"></div>
</body>
<script type="text/javascript">
(function() {
var parent = document.getElementById('parent');
var child = document.getElementById('child');
var grandchild = document.getElementById('grand-child');
parent.addEventListener('click', function(e) {
console.log("parent");
e.stopPropagation();
},true);
child.addEventListener('click', function(e) {
console.log("child");
});
grandchild.addEventListener('click', function(e) {
console.log("grandchild");
});
})();
</script>
</html>