微信小程式 --- 模擬複選框
阿新 • • 發佈:2019-01-31
樣式部分你們自由發揮,反正這裡是什麼都沒寫的,選中和沒選中直接用這個this.data.arrStatus[checkIndex]去判斷就行了,之後你們都懂的~~愛怎麼耍怎麼耍
效果預覽:
js部分
// page/index/index.js
Page({
/**
* 頁面的初始資料
*/
data: {
items: [
{ name: 'USA', value: '美國' },
{ name: 'CHN', value: '中國' },
{ name: 'BRA', value: '巴西' },
{ name: 'JPN' , value: '日本' },
{ name: 'ENG', value: '英國' },
{ name: 'TUR', value: '法國' },
],
arr: [],
arrStatus: []
},
check: function (e) {
//獲取當前選中的值
var checkValue = e.currentTarget.dataset.val;
//獲取當前選中的下標
var checkIndex = e.currentTarget.dataset.index;
//當前選中的取反值
this .data.arrStatus[checkIndex] = !this.data.arrStatus[checkIndex];
if (this.data.arrStatus[checkIndex]) {
//如果當前為選中狀態則將值插入進陣列中
this.data.arr.push(checkValue);
}else{
//如果當前為未選中狀態則將值從陣列中刪除並返回一個新的陣列
for (var i in this.data.arr) {
if (this.data.arr[i] == checkValue) {
this .data.arr.splice(i);
}
}
}
//列印當前所選中的資料
console.log(this.data.arr);
},
/**
* 生命週期函式--監聽頁面載入
*/
onLoad: function (options) {
//設定陣列中每一個數據的狀態
for (var i in this.data.items) {
this.data.arrStatus[i] = false;
}
},
})
wxml部分:
<block wx:for='{{ items }}'>
<text data-index='{{ index }}' data-val='{{ item.value }}' catchtap='check'>{{ item.value }}</text>
</block>