微信小程序 checkbox实现多选复制清空效果

wxml

 1 <text>请勾选你认识的怪物</text>
 2 <checkbox-group bindchange="OnSelect" class="content">
 3   <checkbox class="monster_tag" wx:for="{{monster}}" wx:for-index="index" wx:key="index" value="{{item.name}}"
 4     checked="{{item.checked}}">{{item.name}} LV{{item.lv}} HP{{item.hp}}
 5   </checkbox>
 6 </checkbox-group>
 7 
 8 <view class="btn_box">
 9   <button plain="true" size="mini" bindtap="copy">复制</button>
10   <button plain="true" size="mini" bindtap="clear">清空</button>
11 </view>

js

 1 Page({
 2   data: {
 3     monster: [
 4       { 'id': '1', 'name': '独眼蝙蝠', 'lv': 1, 'hp': 100 },
 5       { 'id': '2', 'name': '彭哆菇', 'lv': 3, 'hp': 300 },
 6       { 'id': '3', 'name': '象牙甲虫', 'lv': 5, 'hp': 500 },
 7       { 'id': '4', 'name': '山岭剑龙', 'lv': 7, 'hp': 700 },
 8       { 'id': '5', 'name': '暴躁的迪米', 'lv': 9, 'hp': 900 },
 9       { 'id': '6', 'name': '山地幼狼', 'lv': 11, 'hp': 1100 },
10       { 'id': '7', 'name': '山地狼王', 'lv': 15, 'hp': 15000 },
11     ],
12     obj: ''
13   },
14 
15   OnClick(e) {
16     console.log('点击了复制按钮')
17     console.log('接受到参数:', e.currentTarget.dataset.value)
18 
19     wx.setClipboardData({
20       data: '要复制的数据',
21       success: function (res) {
22         console.log("复制成功:", res)
23       },
24     })
25   },
26 
27   OnSelect(e) {
28     console.log(e)
29     console.log("勾选了: ", e.detail.value)
30 
31     let { obj, monster } = this.data
32     let { value } = e.detail
33     obj = value
34 
35     for (let i in monster) {
36       monster[i].checked = false
37       for (let o in value) {
38         if (monster[i].name == value[o]) {
39           monster[i].checked = true
40         }
41       }
42     }
43 
44     console.log(obj)
45     console.log(monster)
46 
47     this.setData({
48       obj,
49       monster
50     })
51   },
52 
53   copy() {
54     console.log("点击了复制按钮")
55     let { obj } = this.data
56 
57     if (obj != '') {
58       wx.setClipboardData({
59         data: '' + obj,
60         success: function (res) {
61           console.log("复制成功:", res)
62         },
63       })
64     } else {
65       wx.showToast({
66         title: '未勾选任何数据!',
67         duration: 2000,
68         icon: 'none'
69       })
70     }
71 
72   },
73 
74   clear() {
75     console.log("点击了清空选择按钮")
76     let { obj, monster } = this.data
77 
78     if (obj != '') {
79       obj = ''
80       for (let i in monster) {
81         monster[i].checked = false
82       }
83     } else {
84       wx.showToast({
85         title: '数据为空,不用清理',
86         duration: 2000,
87         icon: 'none'
88       })
89     }
90 
91     console.log(obj, monster)
92 
93     this.setData({
94       obj,
95       monster,
96     })
97   }
98 
99 })

效果图

时间若流水,恍惚间逝去
原文地址:https://www.cnblogs.com/alanshreck/p/14502658.html