微信小程序事件中对象获取

2025-10-21 22:08:04

1、打开小程序开发工具,新建‘myIndex’项目,在项目的pages页面新建page,名为mypage,并在app.json中将mypage设为第一页面

微信小程序事件中对象获取

2、在mypage.wxml中添加三个view标签,代码如下:

<view bindtap='view1tap' class='view1' id ='view1'>

<view bindtap='view2tap' class='view2' id = 'view2'>

<view bindtap='view3tap' class='view3' id='view3'>

</view>

</view>

</view >

微信小程序事件中对象获取

3、在mypage.wxss中,为上面的三个view设置样式,代码如下:

.view1{

width: 100%;

height: 200rpx;

background-color: red;

}

.view2{

width: 50%;

height: 100rpx;

background-color: blue;

}

.view3{

width: 50%;

height: 50rpx;

background-color: wheat;

}

微信小程序事件中对象获取

4、在mypage.js中,为三个view被点击事件添加响应函数,函数中传递点击的对象

view1tap:function(event){

console.log('view1 click');

console.log(event);

},

view2tap:function(event){

console.log('view2 click');

console.log(event);

},

view3tap: function (event) {

console.log('view3 click');

console.log(event);

}

微信小程序事件中对象获取

5、编译运行代码,点击左侧的view3,即最小的view,在console观察打印的内容

微信小程序事件中对象获取

6、展开view3 click下面的currentTarget和target子项,看到了dataset子项 id 值都为view3,但是这两者是有区别的。currentTarget是指当前的对象,target是指触发这个事件的对象。

微信小程序事件中对象获取

7、展开view1 click下面的currentTarget和target子项,看到了dataset子项 id 值分别为view1和view3。因为此事件是view3被点击冒泡到了view1事件。

微信小程序事件中对象获取

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢