原生微信小程序答題用一套代碼實現單選(判斷)和多選


原理:利用三目根據數據的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