# 开发需求
最近在做一个小程序的项目时,要实现一个多选标签的功能,发现动态绑定class名称的时候发现了一些问题,将最后实现的方法记录下来。
# 方法一
<!-- .wxml 文件 -->
// 定义数组中是否包含某个元素的事件,记得要在顶部定义,或者引入wxs,不然不会生效
<wxs module="m1">
var hasItem = function(list,item) {
var boo;
var index = list.indexOf(item)
if (index < 0){
boo = false;
}else{
boo = true;
}
return boo;
}
module.exports.hasItem = hasItem;
</wxs>
<view>
<div class="tags-content">
<div class="title">选择<span>供应</span>产品分类</div>
<div class="content">
<van-grid gutter="10" column-num="3">
<block wx:for="{{list}}" wx:key="curCode">
<!-- 在这里动态绑定class类名 -->
<van-grid-item class="{{m1.hasItem(checkSupplyList,item.curCode)?'on':''}}" use-slot data-name="{{item.curName}}" data-code="{{item.curCode}}"
bindtap="checkSupply">
{{item.curName}}
</van-grid-item>
</block>
</van-grid>
</div>
<div class="bottom-btn">
<button bindtap="next" type="primary">下一步</button>
</div>
</div>
</view>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# 方法二
// hasItem.wxs 中定义
var hasItem = function(list,item) {
var boo;
var index = list.indexOf(item)
if (index < 0){
boo = false;
}else{
boo = true;
}
return boo;
}
module.exports.hasItem = hasItem;
<!-- wxml中引入 -->
<wxs src="../hasItem.wxs" module="hasItem" />
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
记住想要在小程序wxml中使用函数,一定得定义wxs! wxs官方文档