微信小程序自定义多选按钮直接贴代码了
干货分享 · 2020-06-06
本文由源码视像小张提供记录
自定义多选用的非常多,如选课,选喜好,选地点等等,话不多说直接上代码了:
locationValue:[],
locationList:[{
id:1,
name:'郑州',
selected:false
},{
id:2,
name:'北京',
selected:false
},{
id:3,
name:'上海',
selected:false
},{
id:4,
name:'天水',
selected:false
},{
id:5,
name:'深圳',
selected:false
},{
id:6,
name:'青岛',
selected:false
},{
id:7,
name:'巴格达',
selected:false
},{
id:8,
name:'纽约',
selected:false
},{
id:9,
name:'洛杉矶',
selected:false
}]locationValue:用来存放选好的地址,locationList是个地址列表demo
<scroll-view scroll-x class="scroll-h-list" scroll-with-animation scroll-left="{{scrollLeft}}">
<view class="item {{item.selected?'bg-yellow cur text-white':'text-gray'}}" wx:for="{{locationList}}" wx:key="index" bindtap="selectLocation" data-id="{{item.id}}" data-index="{{index}}">
{{item.name}}
</view>
</scroll-view>前端代码是这样的,selectLocation方法用来实现点击事件
//选择所在地
selectLocation(e) {
let index = e.currentTarget.dataset.index;
let location = this.data.locationList[index];
location.selected = !location.selected;
let locationValue = this.data.locationValue;
if(location.selected){
locationValue.push(location.id);
}else{
this.delElement(locationValue,location.id);
}
this.setData({
locationValue:locationValue,
locationList:this.data.locationList
});
console.log(locationValue);
},如果选中了就把值push进locationValue里面,如果取消了选中就删除对应的值,删除函数delElement如下:
//删除数组中指定的元素
delElement:function(arr,ele){
for(var i=0;i<arr.length;i++){
if(ele == arr[i]){
arr.splice(i,1);
return false;
}
}