单个字
新建一个.wxs结尾的文件
function fn(arr, arg) {
var result = {
indexOf: false,
toString: ''
}
result.indexOf = arr.indexOf(arg) > -1;
result.toString = arr.join(","); return result;
}
module.exports.fn = fn;
在wxml文件中引入并使用文件
<wxs src="./search.wxs" module="mysearch" />
<view class="searchresbox" wx:for="{{list}}" wx:for-item="item1">
<block wx:for="{{item1}}">
<text class="{{mysearch.fn(stringRes, item).indexOf?'red':''}}">{{item}}</text>
</block>
</view>
在js文件中
data: {
keylist:['我爱你','打死你','啊啊啊','讨厌啊','不不不'],
list: [],
stringRes:[]
},
getSearchRes(e){
let { keylist } = this.data
var stringRes = e.detail.value.split('')
let list = []
keylist.forEach(e => {
list.push(e.split(''))
})
this.setData({
list:e.detail.value?list:[],
stringRes
})
},
多个文字
在wxml文件中
<view class="searchresbox" wx:for="{{list}}" wx:for-item="item1" catchtap="gotoSearch" data-text="{{item1}}">
<text class="cuIcon-search" style="font-size: 24rpx;margin-right: 12rpx;"></text>
<block wx:for="{{item1}}">
<text wx:if="{{item.key == true}}" class="searchcolor1 searchtext">{{item.str}}</text>
<text wx:else class="searchcolor2 searchtext">{{item.str}}</text>
</block>
</view>
在js文件中
data: {
keylist:['我爱你','打死你','啊啊啊','讨厌啊','不不不'],
list: [],
stringRes:[]
},
getSearchRes(e){
let { keylist } = this.data
var stringRes = e.detail.value
let list = []
if(stringRes){
keylist.forEach(e => {
let reslutDom = this.hilight_word(stringRes,e)
list.push(reslutDom)
})
}
this.setData({
list:e.detail.value?list:[],
stringRes
})
},
hilight_word: function (key, word) {
let idx = word.indexOf(key), t = [];
if (idx > -1) {
if (idx == 0) {
t =this.hilight_word(key, word.substr(key.length));
t.unshift({ key: true, str: key });
return t;
}
if (idx > 0) {
t =this.hilight_word(key, word.substr(idx));
t.unshift({ key: false, str: word.substring(0, idx) });
return t;
}
}
return [{ key: false, str: word }];
},