微信扫描下方二维码 观看效果-动物觅踪
感谢阅读,初学小白,有错指正。
一、功能描述
在上篇文章的基础上,想实现点击搜索图标,跳出一个搜索框,用户可以在搜索框中输入关键字,然后点击回车,搜索结果在下方显示,选中其中一个搜索结果,可以跳转至选中的内容。
描述的比较复杂,这次先展示效果
二、修改内容
点击左侧放大镜搜索图标,出现搜索文本框在这里就不赘述了,可以结合之前的文章进行实现《微信小程序3-显标记信息和弹框》《微信小程序5-图片实现点击动作和动态加载同类数据》,这里主要介绍搜索相关的代码。
在《微信小程序5-图片实现点击动作和动态加载同类数据》中提到图片点击时,触发一个用户可输入搜索的文本框。这次从文本框开始写。
index.wxml修改
<scroll-view animation="{{animationData}}" class="search_box" wx:if="{{showSearchBoxStatus}}">
<input class="search_input" type="text" placeholder="请输入" bindconfirm ="onSearchInput"/>
</scroll-view>
scroll-view:为了实现隐藏搜索框,点击的时候再出现,参照《微信小程序3-显标记信息和弹框》
input:placeholder:显示文本框默认的提示信息
bindconfirm:用户点击输入或回车的时候触发的函数,搜索的实际动作,应该在此函 数中触发。
bindinput:在本次没使用,作用是用户输入1234的时候,会触发回调四次,分别为 1、12、123、1234,而bindconfirm触发的标准是用户有没有点击回车或输入。
<view wx:for="{{ searchResult }}" wx:key="index" bindtap="searchResultView" data-index="{{ index }}">
<view class="search_scrollItem" >
<text class="search_list_text">{{ searchResult[index].title }}</text>
</view>
</view>
wx:for:部分内容可查看《微信小程序5-图片实现点击动作和动态加载同类数据》
bindtap:用户点击搜索结果某一条的时候,将会触发该函数。
searchResult:存储搜索结果的list变量,既存储上文onSearchInput函数的搜索结果。
searchResult[index].title:具体搜索结果的内容。
index.js修改
onSearchInput: function (e) {
var result = [];
var i = 0;
// 搜索结果,填写进result
while (i < tagInfo.length) {
if (tagInfo[i].title.includes(e.detail.value) == true) {
result.push(tagInfo[i])
}
i++;
}
// 判断是否搜到内容,否则直接退出
if (result.length > 0) {
this.setData({
searchResult: result
})
} else {
return
}
// 显示搜索的隐藏框
if (this.data.showSearchListStatus == false) {
this.showBox(this.data.showPageType.searchListType)
}
}
搜索框搜索的时候,触发该函数。
searchResultView: function (result) {
const index = result.currentTarget.dataset.index;
const selectedInfo = this.data.searchResult[index];
// index很重要
// 处理你的逻辑代码
});
其中result.currentTarget.dataset.index很重要,它的值是标记用户在搜索结果中,选中的第几条文本,这样你就可以在该函数内,处理用户选中的结果编号,并实现交互的效果。