微信小程序投票多选案例

在这里插入图片描述

  • 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

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值