小程序?qū)馕鰳?biāo)簽字符串不友好,有時(shí)候要處理一些搜索內(nèi)容、關(guān)鍵字、段落中高亮展示檢索到的匹配文字就會比較麻煩。
[HTML]
<view class="section"> <view class="view-search"> <input class="view-search-input" value="{{keyName}}" placeholder="輸入搜索關(guān)鍵詞" bindinput="bindInput" maxlength="11" /> </view> <scroll-view class="scrollView" scroll-y> <view wx:for="{{searchDataList}}" wx:key="*this"> <view class='oneText'> <text wx:for="{{item.text}}" wx:key="{{index}}" class="{{item == keyName ? 'searchHigh' : '' }}">{{item}}</text> </view> </view> </scroll-view> </view>
[CSS]
.view-search { padding: 12rpx 30rpx; box-sizing: border-box; position: relative; } .view-search-input { height: 70rpx; line-height: 70rpx; border: 2rpx solid #ccc; border-radius: 10rpx; box-sizing: border-box; padding: 0px 70rpx 0px 20rpx; font-size: 32rpx; } .searchHigh { color: #409eff; } .scrollView { height: 80vh; background-color: #F5F5F5; box-sizing: border-box; } .oneText { line-height: 50rpx; margin: 30rpx; text-align: center; color: #9B9B9B; font-size: 32rpx; } .currentText { color: #0099FF; }
[JavaScript]
const app = getApp(); const getInf = (str, key) => str.replace(new RegExp(`${key}`, 'g'), `%%${key}%%`).split('%%'); Page({ data: { keyName: null, primaryListData: [ { "id": "1", "text": "挺不錯的小老弟" }, { "id": "2", "text": "是的,挺不錯" }, ], // 內(nèi)容原始數(shù)組 (如果是后臺請求的數(shù)據(jù),就不需要兩個數(shù)組了)) searchDataList: [ { "id": "1", "text": "挺不錯的小老弟" }, { "id": "2", "text": "是的,挺不錯" }, ], // 用來搜索的復(fù)制數(shù)組 }, // 輸入框正在輸入 bindInput: function (e) { var that = this; that.setData({ keyName: that.trim(e.detail.value) }) that.searchTap(); }, // 搜索關(guān)鍵字 searchTap: function () { var that = this; var data = that.data.primaryListData; var newData = that.data.searchDataList; for (var i = 0; i < data.length; i++) { var dic = data[i]; var newDic = newData[i]; var text = dic["text"]; newDic["text"] = getInf(text, that.data.keyName); } that.setData({ searchDataList: newData, }) }, // 去除首尾的空格 trim: function (s) { return s.replace(/(^\s*)|(\s*$)/g, ""); }, onLoad: function (e) { }, })
工作日 8:30-12:00 14:30-18:00
周六及部分節(jié)假日提供值班服務(wù)