(已解决)微信小程序调查问卷所有题放在一个页面上

最近做一个调查问卷的小程序改需求时遇到了一个问题:

要将所有单选题放在一个页面上,我用了双层循环嵌套将每道题的下标以及每个题对应的选项下标循环出来

但是每个单选的radioChange绑定事件都是同一个函数,造成了如果用户想更改选项那么后台js记录的当前checked的选项不是更改后的选项,而是更改前的选项并且还造成了一道题变成多选的结果

(将所有单选题放在一个页面上)

(radioChange事件控制台输出选择的选项)
在这里插入图片描述

解决思路:

  1. wxml拿到每道题的下标,再拿到每道题对应的选项的下标
  2. radioChange函数用foreach遍历当前题目的选项ABCD的item.checked是否有true,若有true证明之前这道题已经选过
  3. 创建一个变量chongfu,用if语句判断如果foreach遍历结果中有true,则赋值给chongfu=true
  4. 判断chongfu是否为true,再用ifelse语句,若为true,则先pop()之前的选项,再push()更改后的选项装进数组,若为false则直接将选项装进最后提交的答案数组

前端wxml代码:

	<scroll-view scroll-y='true' class="container-scroll" enable-flex='true' wx:for='{{currentQuesiton}}' wx:item='item' wx:key="index" wx:for-index="childindex">
		<view class="container">
			<!-- 标题 -->
			<view class=" title">{{item.questionNo}}、{{item.questionContent}}</view>
			<!-- 选项 -->
			<view class="answer-box">
				<radio-group bindchange="radioChange" data-index="{{childindex}}">
					<label wx:for="{{item.scaleOptions}}" wx:item='item' data-index="{{childindex}}" wx:key="unique" class="item">
						<view>
							<radio value="{{item.option}}" checked="{{item.checked}}" />
						</view>
						<view class="">{{item.optionContent}}</view>
					</label>
				</radio-group>
			</view>
		</view>
	</scroll-view>

js代码

  /**
   * 改变选项 和 记录选项
   */
  radioChange(e) {
    console.log('radio发生change事件,携带value值为:', e.detail.value)
    var index = e.currentTarget.dataset.index;
    const options = this.data.currentQuesiton[index].scaleOptions;

    //多选bug(已解决)
    var chongfu = false;  //一道题只能选一个
    options.forEach((ele, i) => {
      if(options[i].checked === true){
        chongfu = true;
      }
    })
    if(chongfu === true){
       this.data.currentAnswer = e.detail.value;
       this.data.answers.pop();
       this.data.answers.push(String(this.data.currentAnswer));
    }else{
      this.data.currentAnswer = e.detail.value;
      this.data.answers.push(String(this.data.currentAnswer));
    }
    options.forEach((ele, i) => {
      options[i].checked = false;
      options[e.detail.value - 1].checked = true;
    })
  },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值