今天群里有人问了一个问题,怎么实现单选题和多选题在单击时选中,想着反正也没啥事,就写个demo试试看,代码如下:
首先在data里面添加问答题,如下:
data: {
quest: [{
id: 1,
type: 1, //类型,1.单选,2.多选
question: "1.你有女朋友吗?(单选)",
answers: [{
content: 'A.有'
}, {
content: 'B.没有'
}]
}, {
id: 2,
type: 1,
question: "2.目前薪资在哪个范围?(单选)",
answers: [{
content: 'A.3-6k'
}, {
content: 'B.6-8k'
}, {
content: 'C.8-10k'
}, {
content: 'D.10k以上'
}]
}, {
id: 3,
type: 2,
question: "3.你喜欢哪一种编程语言?(多选)",
answers: [{
content: 'A.Java'
}, {
content: 'B.C语言'
}, {
content: 'C.PHP'
}, {
content: 'D.Python'
}, {
content: 'E.JavaScript'
}, {
content: 'F.其他'
}]
}]
},
然后在wxml文件里面显示问答题,代码如下:
<view class='quest_container' wx:for="{{quest}}" wx:key="id" wx:for-index="outterIndex">
<text>{{item.question}}</text>
<view wx:for="{{item.answers}}" wx:key="content" bindtap="answerSelected" data-outidx='{{outterIndex}}' data-idx="{{index}}" class="item {{item.selected?'active':''}}">
<text>{{item.content}}</text>
</view>
</view>
对应的绑定事件如下:
answerSelected(e) {
let outidx = e.currentTarget.dataset.outidx;
let idx = e.currentTarget.dataset.idx;
let question = this.data.quest[outidx];
if (question.type == 1) {
//单选
for (let item of question.answers) {
item.selected = false;
}
question.answers[idx].selected = true;
this.setData({
quest: this.data.quest
});
} else if (question.type == 2) {
//多选
question.answers[idx].selected = !question.answers[idx].selected;
this.setData({
quest: this.data.quest
});
}
},
最终效果如下: