wxml
<view class='button_container'>
<block wx:for="{{buttons}}" wx:key="buttons">
<button style='width: 250rpx;height: 300rpx;' class='{{item.checked?"checked_button":"normal_button"}}' data-id='{{item.id}}' bindtap='checkButtonTap'>{{item.name}}</button>
</block>
</view>
wxss
.button_container{
display: flex;
flex-direction: row;
justify-content: space-around
}
/* 按钮未选中 */
.normal_button{
background: rgb(255, 255, 255)
}
/* 按钮选中 */
.checked_button{
background: rgb(240, 239, 239);
color: white
}
js
Page({
data: {
buttons: [{ id: 1, name: '珍珠' }, { id: 2, name: '红豆' }, { id: 3, name: '寒天' }],
msg:'',
},
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
})
},
})