微信小程序心得四之点击多选并返回状态给后台

在写微信小程序的过程中 特别是有一种需求 就是点击显示选中状态 然后再点击取消选中状态 但是你的数据都是后台发给你 循环出来的样式 非常大的可能就是没给你发state这个状态 这个时候就要自己用for循环循环每一条后端发过来的数据并且加上state这个状态 例如:

let friendArr = JSON.parse(options.friend)
    for (let i = 0; i < friendArr.length; i++) {
      friendArr[i].state = false
    }
    this.setData({
      focusman: friendArr
    })

然后就是根据 点击改变状态 并且最后把选中的状态的选项的index放到一个数组中发给后台‘
也可以用for in 语句

const arr1 = that.data.focusman
          for (var s in arr1) {
          
                arr1[s].status = false
       
            
          }
//点击事件
select: function (e) {
    // console.log(e)
    //index 等于 点击的选项的index
    let index = e.target.dataset.index
    //点击哪个选项就改变这个选项的状态并最终给data中的数组
    this.data.focusman[index].state = !this.data.focusman[index].state
    this.setData({
      focusman: this.data.focusman
    })
    //如果选中的状态是true的话  就把选中的选项的index给一个空数组  否则的话就引用一个可以获得你选中的index这个值来删除数组中的你当前点击的index的方法来删除数组中的你点击的这个选项的index
    if(this.data.focusman[index].state==true){
      this.data.app.push(index)
      console.log(this.data.app)
    }else{
      function arrIntercept(arr, val) {
        var index = arr.indexOf(val)
        if (index > -1) {
          arr.splice(index, 1);
        }
        return arr
      }
     console.log(arrIntercept(this.data.app,index))
    }
    
  },

猜你喜欢

转载自blog.csdn.net/weixin_42790916/article/details/82757605