小程序实现toggleclass功能的问题

<view class='a'>

  <text> Hello {{name}}!</text>

  <block wx:for='{{datas}}' wx:key='u'>

    <button data-index='{{index}}' class='{{index==id?classname:""}}' data-m='{{t==index}}' bindtap="changeName"> {{item.data}} </button>

  </block>

</view>

上面是wxml 三个btn,想实现点击添加classname(class='m'),下面是js部分,可以实现点击添加class='m'功能,但是当点击已添加class='m'按钮时,如何移除此时按钮的class?试了半天还没有想到办法


var datas = {

  dataa: [{

    data: 'click me1'

  }, {

    data: 'click me2'

  }, {

    data: 'click me3'

  },

  ]

}

Page({

  data: { name: 'lili', classname:'', datas: datas.dataa },

  changeName: function (e) {

    var x = e.currentTarget.dataset.index

    console.log(e.detail)

    this.setData({

      name: 'MINA',

      id: x,

      classname:'m',

    })

    ...


ABOUTYOU
浏览 550回答 2
2回答

慕神8447489

你可以用一个数组来存class状态。<button data-index='{{index}}' class='{{index+1==selectedList[index]?"m":""}}' bindtap="changeName"> {{item.data}} </button>Page({&nbsp; data: { name: 'lili', selectedList:[], datas: datas.dataa },&nbsp; changeName: function (e) {&nbsp; &nbsp; var x = e.currentTarget.dataset.index&nbsp; &nbsp; this.setData({&nbsp; &nbsp; &nbsp; &nbsp; ['selectedList[' + x + ']']: this.data.selectedList[x]?null:x+1&nbsp; &nbsp; })})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript