最近做一个调查问卷的小程序改需求时遇到了一个问题:
要将所有单选题放在一个页面上,我用了双层循环嵌套将每道题的下标以及每个题对应的选项下标循环出来
但是每个单选的radioChange绑定事件都是同一个函数,造成了如果用户想更改选项那么后台js记录的当前checked的选项不是更改后的选项,而是更改前的选项并且还造成了一道题变成多选的结果
(将所有单选题放在一个页面上)
(radioChange事件控制台输出选择的选项)
解决思路:
- wxml拿到每道题的下标,再拿到每道题对应的选项的下标
- radioChange函数用foreach遍历当前题目的选项ABCD的item.checked是否有true,若有true证明之前这道题已经选过
- 创建一个变量chongfu,用if语句判断如果foreach遍历结果中有true,则赋值给chongfu=true
- 判断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;
})
},