需求:在小程序搜索关键字的时候,需要搜索结果中的关键字高亮
wxml页面
<block wx:for="{{result_list}}" wx:for-item="sitem" wx:key="sitem">
<view class="search_res_list" bindtap="resultClick" data-id="{{sitem.id}}">
<view class="res_list_title">
<block wx:for="{{sitem.titleWords}}" wx:key="item">
<text class="{{item.match ? 'key_light' : ''}}">{{item.word}}</text>
</block>
</view>
<view class="res_list_sec">
<block wx:for="{{sitem.textWords}}" wx:key="item">
<text class="{{item.match ? 'key_light' : ''}}">{{item.word}}</text>
</block>
</view>
</view>
</block>
js页面
/**
* 引用关键字
* this: this;
* newVal: 搜索结果数组
*/
function returnItems(_this, newVal) {
if (newVal.length <= 0) {
return;
}
let items = [];
try{
items = (newVal).map(item => {
return {
...item,
titleWords: util.matchKeyword(this.data.inputKeys, item.title),
textWords: util.matchKeyword(this.data.inputKeys, item.context)
}
})
}catch(err){console.log(err)}
return items
}
/**
* 搜索关键字标红
* key: 搜索关键字
* str: 搜索结果字符串
*/
function matchKeyword(key, str) {
let that = this;
let idx = str.indexOf(key);
let t = [];
if (idx > -1) {
if (idx == 0) {
t = matchKeyword(key, str.substr(key.length));
t.unshift({
match: true,
word: key
});
return t;
}
if (idx > 0) {
t = matchKeyword(key, str.substr(idx));
t.unshift({
match: false,
word: str.substring(0, idx)
});
return t;
}
}
return [{
match: false,
word: str
}];
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。