原生微信小程序答题用一套代码实现单选(判断)和多选


原理:利用三目根据数据的type判断是什么类型的题,然后再进行渲染颜色

没有废话直接给代码

wxml :
<view class="answer-choice" wx:for="{{list[countIndex].content}}" wx:key="index"> <view class="viewTitle {{list[countIndex].type == 2 ?(duoXuan!=listT[index]? 'red': ''): (index==danXuan?'red': '' )}}" bindtap="option" data-type="{{list[countIndex].type==1? index:(list[countIndex].type==2? duoXuan:'') }}" data-index="{{index}}">{{item}}</view> </view> <view class="answer-confirm" bindtap="next">确认</view>

js
data中
data: {
wan: 1,
duoXuan: 0,
danXuan: x,
listT: [0, 0, 0, 0], //选择情况
list: [
{ id: 1, question: 22+121414dadad1242112, content: [123, 456756, 22, 6868], val: [0, 0, 1, 0], type: 1 },
{ id: 1, question: 11+6868+1214141242112, content: [11, 456756, 345, 6868], val: [1, 0, 0, 1], type: 2 },
{ id: 1, question: 33+44+141412哥哥42112, content: [123, 456756, 33, 6868, 44], val: [0, 0, 1, 0, 1], type: 2 },
{ id: 1, question: 121+4141242112, content: [123, 121, 345, 6868], val: [0, 1, 0, 0], type: 1 },
],
type: [0, 单选题, 多选题, 判断题,],
listCount: 4,
countIndex: 0,

方法:
option: function (e) {
let that = this
if (that.data.list[that.data.countIndex].type == 2) {
if (that.data.listT[e.target.dataset.index] == 0) {
let arr = that.data.listT
arr[e.target.dataset.index] = 1
that.setData({
listT: arr
})
} else if (that.data.listT[e.target.dataset.index] == 1) {
let arr = that.data.listT
arr[e.target.dataset.index] = 0
that.setData({
listT: arr
})
}
console.log(that.data.listT);
} else {
console.log(e.target.dataset.index);
that.setData({
danXuan: e.target.dataset.index
})
}
},

css:
.viewTitle {
width: 90%;
margin: 2% auto;
padding: 5px 10px;
font-size: 26rpx;
background-color: #e8e8e8;
border-radius: 5px;
}

.red {
background-color: red;
}

.green {
background-color: rgb(12, 245, 32);
}

如果你还要加上在点击确认后的正确答案颜色的话 就在data里加个值来判断当前是否点击确认,wxml里的 class="viewTitle {{加上三目判断就完了}}"


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM