实现单向选择题和多项选择题的选中状态-不使用radio和CheckBox

这篇博客探讨了微信小程序中单选题和多选题的实现方式,包括数据结构设计、事件处理函数以及选中状态的管理。在单选题中,使用`wx:for`指令遍历选项,并通过`bindtap`事件处理选中状态。而在多选题中,每个选项增加了`isSelect`字段来跟踪选中状态,通过改变这一字段实现选项的切换。博客还展示了相关的代码片段和实际效果。

题目一是单选
题目二、三是多选,
多选比单选多个字段 isSelect
data里面的内容

//单选参考数据
option:[
       {options:'A',optionss:'选项A'},
       {options:'B',optionss:'选项B'},
       {options:'C',optionss:'选项C'},
       {options:'D',optionss:'选项D'}
     ],
//多选参考数据
option2:[
  //,'B.选项1b','C.选项c','D.选项d'
  {options:'A',optionss:'选项A',isSelect:false},
  {options:'B',optionss:'选项B',isSelect:false},
  {options:'C',optionss:'选项C',isSelect:false},
  {options:'D',optionss:'选项D',isSelect:false}
]
suoy:'',

单选

<view class="top_test_bottom_option {{suoy==item.options?'selected':''}}" 
wx:for="{{option}}" data-id="{{item.options}}"
bindtap="select1">

解释:
{{suoy==item.options?‘selected’:’’}}这个是个类名,用来修改选中选项的样式,
{{item.options}}用来JS中获取选中的第几个选项的索引
bindtap=“select1” 方法名

 select1:function(e){
    var selectid = e.target.dataset.id  //获取题号的索引
     this.setData({
       suoy: selectid 
     });
     console.log(id+"" + this.data.suoy);  //可以调试打印
  },

选中的样式

.selected{background-color:rgba(41,125,96,0.5)} 

多选

<view class="top_test_bottom_option {{item.options?'selected':''}}" 
wx:for="{{option}}" data-id="{{item.options}}" data-index='{{index}}'
bindtap="select2">

同上,但是这个select2方法里面的内容不太一样;如下:

select2:function(e){
    var index = e.currentTarget.dataset.index;  //获取选项索引
    var item = this.data.option[index];  //获取选中的那一行数据
    item.isSelect= !item.isSelect;
    this.setData({
      test: this.data.test,
    });
  },

效果图如下:
在这里插入图片描述
在这里插入图片描述

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值