<block wx:for="{{items}}" wx:for-item="v" wx:key="k" wx:for-index="index">
<view class="instlist" data-index="{{index}}" data-value="{{v.value}}" bindtap="checkLabs">
<image src="{{v.src}}" class="image {{v.checked?'cur':''}}"></image>
<text class='text'>{{v.value}}</text>
</view>
</block>
------------------------------
items: [{
id: 1,
"src": "../../../../images/lvxing.png",
value: "音乐",
checked: false
}, {
id: 2,
"src": "../../../../images/lvxing.png",
value: "艺术",
checked: false
}, {
id: 3,
"src": "../../../../images/lvxing.png",
value: "游戏",
checked: false
}, {
id: 4,
"src": "../../../../images/lvxing.png",
value: "追星",
checked: false
}],
arr: [], //标签数组:用来存储选中的值
//选择标签方法
checkLabs(e) {
var that = this,
index = e.currentTarget.dataset.index,
value = e.currentTarget.dataset.value,
items = that.data.items,
arr = that.data.arr,
val = items[index].checked, //点击前的值
limitNum = 5,
curNum = 0; //已选择数量
//选中累加
for (var i in items) {
if (items[i].checked) {
curNum += 1;
}
}
if (!val) {
if (curNum == limitNum) {
wx.showModal({
content: '选择数量不能超过' + limitNum + '个',
showCancel: false
})
return;
}
arr.push(value);
} else {
for (var i in arr) {
if (arr[i] == value) {
arr.splice(i, 1);
}
}
}
items[index].checked = !val;
that.setData({
items: items,
arr: arr
})
console.log(arr)
},
//默认选中为true的
selectEd(e) {
var that = this,
arr = that.data.arr,
items = that.data.items
for (var i = 0; i < items.length; i++) {
if (items[i].checked) {
var value = items[i].value;
arr.push(value);
that.setData({
items: items,
arr: arr
})
}
}
},
end: function (e) {
console.log(this.data.arr)
wx.setStorageSync("like", this.data.arr)
setTimeout(function () {
//获取页面栈
var pages = getCurrentPages();
if (pages.length > 1) {
//上一个页面实例对象
var prePage = pages[pages.length - 2];
prePage.changeResumeBasic(that.data.arr)
}
wx.navigateBack({
delta: 1
})
}, 1000);
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.selectEd();
},
微信小程序中实现标签元素多选并限制数量
最新推荐文章于 2024-09-15 17:41:01 发布