单选
多选
①wxml--样式选中改变是通过三元运算符实现的
<view class='button_container'>
<block wx:for="{{buttons}}" wx:key="buttons">
<button class='{{item.checked?"checked_button":"normal_button"}}' data-id='{{item.id}}' bindtap='checkButtonTap'>{{item.checked}}11</button>
</block>
</view>
<text>{{msg}}</text>
②wxss
/**index.wxss**/
page {
height: 100vh;
display: flex;
flex-direction: column;
}
.button_container{
display: flex;
flex-direction: row;
justify-content: space-around
}
/* 按钮未选中 */
.normal_button{
background: greenyellow
}
/* 按钮选中 */
.checked_button{
background: red;
color: white
}
③js
单选--记得在wxml中修改绑定方法
bindtap='radioButtonTap'
多选--记得在wxml中修改绑定方法
bindtap='checkButtonTap'
Page({
data: {
buttons: [{ id: 1, name: '银色',checked:false }, { id: 2, name: '白色',checked:false }, { id: 3, name: '黑色',checked:false }],
msg:'',
},
onLoad: function (options) {
console.log(options)
this.data.buttons[0].checked=true;
this.setData({
buttons: this.data.buttons,
})
console.log(this.data.buttons)
},
// 单选
radioButtonTap: function (e) {
console.log(e)
let id = e.currentTarget.dataset.id
console.log(id)
for (let i = 0; i < this.data.buttons.length; i++) {
if (this.data.buttons[i].id == id) {
//当前点击的位置为true即选中
this.data.buttons[i].checked = true;
}
else {
//其他的位置为false
this.data.buttons[i].checked = false;
}
}
this.setData({
buttons: this.data.buttons,
msg: "id:"+id
})
},
// 多选
checkButtonTap:function(e){
console.log(e)
let id = e.currentTarget.dataset.id
console.log(id)
for (let i = 0; i < this.data.buttons.length; i++) {
if (this.data.buttons[i].id == id) {
if (this.data.buttons[i].checked == true) {
this.data.buttons[i].checked = false;
} else {
this.data.buttons[i].checked = true;
}
}
}
this.setData({
buttons: this.data.buttons,
msg: "id:"+id
})
},
})