微信小程序如何实现单选按钮

发布时间:2022-07-19 09:38:16 作者:iii
来源:亿速云 阅读:235

这篇文章主要介绍“微信小程序如何实现单选按钮”,在日常操作中,相信很多人在微信小程序如何实现单选按钮问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”微信小程序如何实现单选按钮”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

逻辑

举例, 两选一 , 默认选中第一个;效果图如下:

.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文件 :

Page({
  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
  })
  }
})

.wxss文件 :

.button_container{
  display: flex;
  flex-direction: row;
  justify-content: space-around
  }
  
  /* 按钮未选中 */
 .normal_button{
  background: white;
  }
  
  /* 按钮选中 */
  .checked_button{
  background: #36ab60;
  color: white
  }```

到此,关于“微信小程序如何实现单选按钮”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

推荐阅读:
  1. 微信小程序如何实现滑动
  2. 微信小程序如何实现tabBar

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

微信小程序

上一篇:ResizeObserver API如何使用

下一篇:Golang中Interface接口的三个特性是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》