微信小程序系列八:使用view实现全选,单选

原理:

    根据数据的checked属性值判断是否处于选中状态

注意:

   样式可以自己调整,这里不再添加

wxml:

<block wx:for="{{list}}" wx:key="*this.index">
  <view data-index="{{index}}" data-name="{{item.id}}" class="{{item.checked==true?'red bc':'bc'}}"bindtap='select'>
    {{item.name}}
  </view>
</block>
<button bindtap='selectAll'>全选</button>

js:

Page({

  /**
   * 页面的初始数据
   */
  data: {
    list:[
      { id: 1, name: 1, checked:false},
      { id: 2, name: 2, checked: false },
      { id: 3, name: 3, checked: false },
      { id: 4, name: 4, checked: false },
    ],
    select:[]
  },
  //单选
  select:function(e){
    let selectValue = e.currentTarget.dataset.name
    let index = e.currentTarget.dataset.index;
    let list = this.data.list
    let newli = 'list[' + index +'].checked';
    this.setData({
      [newli]: !this.data.list[index].checked
    })
    let li2 = this.data.list[index].checked
    if (li2==false){
      for (let i in this.data.select) {
        if (this.data.select[i] == selectValue) {
          this.data.select.splice(i,1);
        }
      }
    } else{
      this.data.select.push(selectValue);
    }
    console.log(this.data.select)
  },
  //全选,取消全选
  selectAll:function(e){
    let list=this.data.list;
    for(let i=0;i<list.length;i++){
      let newli = 'list[' + i + '].checked';
      this.data.select.push(this.data.list[i].id);
      this.setData({
        [newli]: !this.data.list[i].checked
      })
    }
    console.log(this.data.select)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  
  }
})

猜你喜欢

转载自blog.csdn.net/stp_zsj/article/details/81979669
今日推荐