📦 归档笔记 — 原创建于 WizNote,仅作归档展示;观点以当年为准,非最新。

响应事件和事件冒泡/阻止事件冒泡

创建时间2019-09-24最后修改2019-10-14原位置/程序员成长之旅/微信小程序开发学习/笔记/字数349图片/附件4
目录:程序员成长之旅/微信小程序开发学习/笔记

什么是事件冒泡?

当事件发生后,这个事件就要开始传播(从里到外或者从外向里)。

比如子元素触发了事件后会向父元素冒泡,从而触发父元素事件.

比如现在有一段代码


<view class="father default" bind:tap="onFather">

<view class="son default" bind:tap="onSon"></view>

</view>

onFather:function(){

console.log("onFather")

},

onSon:function(){

console.log("onSon")

},
🖼 图片占位(归档模式)图片见原始导出:https://oss.trustme.anyingiit.com/images/20190924200922.png

在点击son标签后就会观察到,先触发了son事件,后触发了father事件

🖼 图片占位(归档模式)图片见原始导出:https://oss.trustme.anyingiit.com/images/20190924201143.png
🖼 图片占位(归档模式)图片见原始导出:https://oss.trustme.anyingiit.com/images/20190924201204.png

而点击father元素就如同所想象的那样,会触发father事件,不做演示了

那么在小程序内有的时候我们不想事件冒泡,该如何去做?

阻止事件冒泡

只需要在wxml内将bind:tap修改为catch:tap即可


<view class="father default" bind:tap="onFather">

<view class="son default" catch:tap="onSon"></view>

</view>

接下来进行点击后就会发现,尽管father是bind:tap事件,但是son内使用了catch:tap阻止了冒泡

🖼 图片占位(归档模式)图片见原始导出:https://oss.trustme.anyingiit.com/images/20190924201646.png

附录

附源码


.default{

border: red solid 2rpx;

}

.father{

display: flex;

flex-direction: column;

align-items: center;

margin-top: 30rpx;

width: 200rpx;

height:100rpx;

}

.father > .son{

margin-top: 25rpx;

width: 100rpx;

height: 50rpx;

}

<view class="father default" bind:tap="onFather">

<view class="son default" catch:tap="onSon"></view>

</view>

onFather:function(){

console.log("onFather")

},

onSon:function(){

console.log("onSon")

},