wxml:
<view class='weui-font'>
<block wx:for="{{item.title}}" wx:key="*this" wx:for-item="items">
<text wx:if="{{items.key == true}}" style="color:red;">{{items.str}}</text>
<text wx:else>{{items.str}}</text>
</block>
</view>
js
value = '环网柜';
var data = JSON.parse(res.Content).rows;
// 将标题已关键字拆开成数组
for (let i = 0; i < data.length; i++) {
data[i].title = that.hilight_word(value, data[i].title);
}
// 根据搜索字分割字符
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 }];
}
效果如下