小程序搜索框的实现和搜索历史记录的实现
这段时间自学小程序编程,从组件到API的学习后,编写的第一个较为综合的小案列,编写搜索框对初学者来说最重要也是最难理解的就是定位和布局:position和display,大家一定要先把这两个属性理解透彻。这里暂时没有写点击各组件之后对应的事件,
.wxml
.mxss
————————————
- 2.也可以利用label组件让搜索框看着更高级一点,如下
.wxml
这里定义的bindtap事件,即点击之后label隐藏
.wxss
- 三,搜索历史记录的实现
- history.unshift is not a function; [Component] Event Handler Error @ pages/index/index#bound bindInputConfirm
TypeError: history.unshift is not a function遇到这个错误是因为history的数据类型不是数组, - 下面的程序实现历史框,但是有一个逻辑存在问题暂时没能解决,就是当清除搜索记录后,点击搜索框,搜索框会显示出来,总找不到原因
.wxss
.js
-
Page({
data: {
labelShowed:false, //label组件的隐藏
inputValue:"", //输入框的初始内容
historyValue:[],//存储的历史数据
history_flag:false,//历史框的显示
},
bindLabelShowed:function(){
this.setData({
labelShowed:true
});
},
//输入完成确认,并且储存搜索的内容,后续显示在历史窗口
bindInputConfirm:function(e){
var value = e.detail.value;
var history = this.data.historyValue || []; //保证history是数组类型,否则unshitt()会出错,特别是适用wx.removeStorageSync的时候
//如果输入内容为空是执行
if( value == ""){
wx.showToast({
title: '请输入内容',
});
setTimeout(() =>{
this.setData({
showToast:false
});
},1500);
}
//如果不为空执行
else{
history.unshift(value); //输入数据放到historyValue数组中
wx.setStorageSync('history', history)//存储数据
this.setData({
historyValue:history,
history_flag:true,
})
};
console.log(wx.getStorageSync('history'));
},
//清除输入框内容
bindClearInput:function(){
this.setData({
inputValue:"",
})
},
bindfocus:function(e){
console.log(e);
// var value =wx.getStorageSync('history');
console.log("-----value---");
console.log(wx.getStorageSync('history'));
if( wx.getStorageSync('history') !== ""||[]){
this.setData({
history_flag:true,
})
}else{
this.setData({
history_flag:false,
})
}
},
//清除历史数据,注意这里是给historyValue为空,后面使用unshift
bindClearHistory:function(){
wx.removeStorageSync("history")
this.setData({
historyValue:"",
history_flag:false,
})
},
//输入框获取焦点,显示历史数据
bindInput:function(){
this.setData({
history_flag:true,
})
},
//删除history的数据
bindDeleteHistory:function(e){
console.log(e)
var history = this.data.historyValue;
var id = e.currentTarget.id;
var newHistory = [];
var temp = 0;
for( let i = 0; i < history.length; i++){
if( history.length == 1 && i == 0){
this.setData({
historyValue:"",
history_flag:false,
})
}
if(i == id){
continue;
}
newHistory[temp] = history[i];
temp++;
this.setData({
historyValue:newHistory,
})
}
},
//事件处理函数
bindViewTap: function() {
wx.navigateTo({
url: '../logs/logs'
})
},
onLoad: function () {
var history = wx.getStorageSync('history')||[];
this.setData({
historyValue:history,
})
},
})