小程序,JS,设置checbox最多被选中三个

wxml
  
    
  
  {{text}}

js

Page({
  /**
   * 页面的初始数据
   */
  data: {
    text:"请选择",
    items: [
      { name: '1', value: '干皮' },
      { name: '2', value: '油皮' },
      { name: '3', value: '敏感肌' },
      { name: '4', value: '痘痘肌' },
      { name: '5', value: '混干皮' },
      { name: '6', value: '混油皮' },
      { name: '7', value: '中性皮肤' },
    ]
  },
//设置checbox最多被选中三个
  checkboxChange: function (e) {
    var that = this;
    var skin = e.detail.value
    //新建数组全部设置为没被选中
    var new_itmes = [
      { name: '1', value: '干皮' },
      { name: '2', value: '油皮' },
      { name: '3', value: '敏感肌' },
      { name: '4', value: '痘痘肌' },
      { name: '5', value: '混干皮' },
      { name: '6', value: '混油皮' },
      { name: '7', value: '中性皮肤' },
    ]
    if (skin.length > 3) {
      //取出倒数三个值
      var key1 = skin[skin.length - 1];
      var key2 = skin[skin.length - 2];
      var key3 = skin[skin.length - 3];
      //设置最后三个值为选中状态
      new_itmes[key1 - 1]['checked'] = 'true'
      new_itmes[key2 - 1]['checked'] = 'true'
      new_itmes[key3 - 1]['checked'] = 'true'

      //删除被选中的第一个值
      skin.splice(0, 1);
    } else {
      //被选中少于三个,直接设置被选中
      for (var i = 0; i < skin.length; i++) {
        var key = skin[i]
        new_itmes[key - 1]['checked'] = 'true'
      }
    }
    //拼接文字显示
    var text = [];
    for (var i = 0; i < skin.length; i++) {
      var key = skin[i]
      text[i] = that.data.items[key - 1]['value']
    }
    text = text.join("、")
    //存入
    that.setData({
      skin: skin,
      text: text,
      items: new_itmes
    })
  }
})

你可能感兴趣的:(小程序)