微信小程序投票多選案例

在這裏插入圖片描述

  • index.wxml
<view>
    <view class="page__hd">

        <view class="weui-cells weui-cells_after-title">
            <view class="weui-cell weui-cell_input">
                <view class="weui-cell__hd">
                    <view class="weui-label">多選項</view>
                </view>
                <view class="weui-cell__bd">
                    <input class="weui-input" placeholder="多選項" bindinput="countInput" value='{{ count }}'/>
                </view>
            </view>
        </view>
        <view class='member' wx:for = "{{ members}}" wx:for-item = "member" wx:key="*this" data-id="{{ member.id }}" bindtap='click'>
              <view>
                <text>{{ member.name  }}</text>
              <wxs module="tools" src="../../utils/arrayFilter.wxs"></wxs>
              <image wx-if="{{tools.isInArray(member.id,selecteds) == true}}" class='selected' src="../../imgs/selected.png" mode="cover"></image>
            </view>
        </view>
    </view>
</view>
  • index.js
const app = getApp()

Page({
  data: {
    members: [
      {
        id : 1,
        name: '雨雨'
      },
      {
        id: 2,
        name: '蘇蘇'
      },
      {
        id: 3,
        name: '哈哈'
      },
      {
        id: 4,
        name: '嘻嘻'
      },
      {
        id: 5,
        name: '呵呵'
      },
      {
        id: 6,
        name: '兔兔'
      }

    ],
    //多選數量
    count: 2,
    //選中項的數組
    selecteds: []
  },
  click: function (e) {
    let id = e.currentTarget.dataset.id;
    let array = this.data.selecteds;
    if (this.isInArray(id, array) == true) {
      console.log('id:' + id +'已經被選中')
    } else {
      //如果數組的長度大於或等於count,則刪除數組第一個 並把後面的id添加到數組中
      if (array.length >= this.data.count) {
        //移除數組左邊第一位
        array.shift();
      } 
      array.push(id)
    }

    this.setData({
      selecteds: array
    })
  },
  //判斷元素是否在數組中
  isInArray: function (value, array) {
    for (var i = 0; i < array.length; i++) {
      if (value == array[i]) {
        return true;
      }
    }
    return false;
  },
  //動態設置選中項的值
  countInput: function (e) {
    this.setData({
      count: e.detail.value
    })
  }
})

  • index.wxss
/**index.wxss**/
.member{
  background-color: white;
  margin-top: 5px;
  padding: 10px;
  font-size: 14px;
  
}

.selected {
  width: 48rpx;
  height: 48rpx;
  float: right;
}
  • arrayFilter
var isInArray = function (value, array) {
  for (var i = 0; i < array.length; i++) {
    if (value == array[i]) {
      return true;
    }
  }
  return false;
}

module.exports = {
  isInArray: isInArray
}

Demo地址:https://github.com/niezhiliang/selected-many-demo

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章