The problem of Mini Program's realization of toggleclass function

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

above are the three btn, of wxml who want to click to add classname (class="m"), and the following is the js section, which can realize the click to add class="m" function, but when you click the added class="m" button, how to remove the class? of the button at this time After trying for a long time, I haven"t thought of a way

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

you can use an array to store class status.

<button data-index='{{index}}' class='{{index+1==selectedList[index]?"m":""}}' bindtap="changeName"> {{item.data}} </button>

Page({
  data: { name: 'lili', selectedList:[], datas: datas.dataa },
  changeName: function (e) {
    var x = e.currentTarget.dataset.index
    this.setData({
        ['selectedList[' + x + ']']: this.data.selectedList[x]?null:x+1
    })
})

you have only one variable to control so many things.
add a value to each item to control whether or not to add classname

Menu