什么是事件冒泡
布局结构如下图

一共单层元素
从外到里依次:div、p、span
每个元素都有单机事件
当单击div触发弹出box
当单击p标签时依次弹出:test、box
当单击span标签依次弹出:inner、test、box
这个即为事件冒泡
从最里层冒泡到最外层
如何阻止
很多时候我们不希望事件冒泡
也就是我点击p的时候只弹出test
点击span时候只弹出inner
1.event.stopPropagation()
- <body>
- <div style="width: 200px;height: 200px;background: red;margin: 200px auto;" onclick="box()">
- <p onclick="test()" style="background: blue">
- wubin.pro <br>
- <span style="background: green" onclick="inner(event)">武斌博客</span>
- </p>
- </div>
- <script>
- function inner() {
- alert('inner');
- event.stopPropagation();
- }
- function test() {
- alert('test')
- }
- function box(event) {
- alert('box')
- }
- </script>
- </body>
这个时候再点击子钦博客时
只是弹出inner
2.return false
- <div style="width: 200px;height: 200px;background: red;margin: 200px auto;" >
- <p style="background: blue">
- wubin.pro <br>
- <span style="background: green" >武斌博客</span>
- </p>
- </div>
- <script>
- $(function () {
- $('span').click(function(){
- alert('inner');
- return false;
- })
- $('p').click(function(){
- alert('test');
- })
- $('div').click(function(){
- alert('box');
- })
- })
- </script>
效果跟第一种相同
都可以阻止事件冒泡
return false与event.stopPropagation()区别
我们将以上代码修改为:
- <div style="width: 200px;height: 200px;background: red;margin: 200px auto;" >
- <p style="background: blue">
- wubin.pro <br>
- <a href="https://wubin.pro" style="background: green" >子钦博客</a>
- </p>
- </div>
- <script>
- $(function () {
- $('a').click(function(event){
- alert('inner');
- // return false;
- event.stopPropagation();
- })
- $('p').click(function(){
- alert('test');
- })
- $('div').click(function(){
- alert('box');
- })
- })
- </script>
可以看出
当使用return false时
a标签的默认行(跳转页面)为也会被阻止
当使用event.stopPropagation()时
先弹出inner
然后页面跳转
总结
- <div style="width: 200px;height: 200px;background: red;margin: 200px auto;" >
- <p style="background: blue">
- wubin.pro <br>
- <a href="https://wubin.pro" style="background: green" >子钦博客</a>
- </p>
- </div>
- <script>
- $(function () {
- $('a').click(function(event){
- alert('inner');
- // return false;
- // event.stopPropagation();
- event.preventDefault();
- })
- $('p').click(function(){
- alert('test');
- })
- $('div').click(function(){
- alert('box');
- })
- })
- </script>
return false:阻止事件冒泡和默认行为
event.stopPropagation():单独阻止事件冒泡
event.preventDefault():单独阻止默认行为