stopPropagation 和stopImmediatePropagation区别

时间:2022-08-31 13:01:27

1、示例代码

<!DOCTYPE html>
<html lang="zh"> <head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>stopPropagation 和stopImmediatePropagation区别</title>
</head> <body>
<div id="app1">
<div id="app2">
<div id="app3">
test
</div>
</div>
</div>
<script type="text/javascript">
let app1 = document.getElementById('app1'),
app2 = document.getElementById('app2'),
app3 = document.getElementById('app3');
app1.addEventListener('click', e => {
alert('第二次执行')
},false)
app3.addEventListener('click', e => {
// e.stopPropagation()
// e.stopImmediatePropagation()
alert('第一次执行')
},false)
app3.addEventListener('click', e => {
alert('app2第二次执行')
},false)
</script>
</body> </html>

2、区别

stopPropagation 和stopImmediatePropagation都能防止事件向父节点冒泡。

stopImmediatePropagation还能阻止该元素剩余的其他事件处理函数的执行。即加上dom1上绑定了2个click事件,在第一个click事件上执行了e.stopImmediatePropagation()后,第二个click事件不会执行。

参考:http://www.365mini.com/page/jquery-event-stopimmediatepropagation.htm