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

程序员成长之旅 · 程序员成长之旅/微信小程序开发学习/笔记 · 349 字

什么是事件冒泡?

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

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

比如现在有一段代码


<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")

},

最后长这个样子

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

而点击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阻止了冒泡


附录

附源码


.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")

},