微信小程序 - 绑定事件 bindtap(包括是否传入参数)

  小程序绑定事件的方式有很多种,这里我只对bindtap的绑定方式进行介绍,其他的绑定方式也是差不多这样的。

1、不带参数的绑定方式

index.wxml文件中:share表示绑定的事件名称

<view class=enjoy bindtap=share>立即分享</view>

index.js文件中:

share(){
    console.log(分享。。。。)
}

2、带参数的绑定方式

index.wxml文件中:   share表示绑定的事件名称,data-id对应的是要传递过去的参数,data- 后面的名称可以自定义,在js文件中要拿到这个参数就要对应的点出data- 后面的自定义名称

<view wx:for="{
         
  {titleList}}" wx:for-index="index" wx:for-item="itemTitle" wx:key="index+itemTitle" bindtap=getLists data-id="{
         
  {itemTitle.bid}}">
    <view>{
         
  {itemTitle.title}}</view>
    <view class=line></view>
</view>

index.js文件中:   因为wxml文件中 data- 后面的自定义名称是 id,所以在这里直接通过 e.currentTarget.dataset.id 取出来即可

getLists(e) {
    // 拿到对应参数 有两种方式都可以拿到对应的参数
    console.log(e---->, e.currentTarget.dataset.id)
    //或者
    console.log(e.target.dataset.id---->, e.target.dataset.id)
}
经验分享 程序员 微信小程序 职场和发展