首页 > 技术文章 > 微信小程序 单选按钮 最佳

lsyy2017 2019-09-21 20:41 原文

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='radioButtonTap'>{{item.name}}</button>
</block>
</view>
 
js;
data:{
buttons: [{ id: 1, name: '失物招领' }, { id: 2, name: '寻物启事' }]
}
onLoad: function() {//默认选了第一个
this.data.buttons[0].checked = true;
this.setData({
buttons: 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
})
},
 
css:
.button_container{
display: flex;
flex-direction: row;
justify-content: space-around
}
/* 按钮未选中 */
.normal_button{
background: white;
}
/* 按钮选中 */
.checked_button{
background: #36ab60;
color: white
}

推荐阅读