搜尋關鍵字變紅
阿新 • • 發佈:2018-12-16
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 }]; }
效果如下