小程序搜索框历史记录,去除重复搜索内容,限制显示条数

在这里插入图片描述
以上为搜索界面

小程序wxml页面

<input type="text" class="weui-search-bar__input" bindinput="input_key" bindconfirm="Load" value="{{input_key}}" />
<view class="weui-icon-clear" wx:if="{{input_key.length > 0}}" bindtap="clearInput">
   <icon type="clear" size="12"></icon>
</view>
<view class="weui-search-bar__cancel-btn" bindtap="Load" data-type="1">搜索</view>

<view style="display: flex;align-items: center; margin-top:5px;">
    <text class="titleHot">历史记录</text>
    <icon class="clearHistory" type="clear" size="12" bindtap="remove"></icon>
</view>
<view class="listHotCi">
   <view  wx:for="{{history}}" class="hotCiText" data-id="{{item.name}}" wx:key="item" bindtap="historyJiLu">
        <text >{{item.name}}</text>
   </view>
</view>

小程序js页面
历史记录是先把获取到的数据,加入缓存,再取到缓存中的数据,加到wxml需要用到的数组里,再判断数组中是否已存在时,最开始使用indexOf,但是返回值一直都是-1,解决方法和疑问在下一个文档里

Page({
  data: {
    input_key: '',
    history:[],
    splist: []
  },
  Load: function (tag) {
    var that = this;
    if (this.data.input_key == "" ){
    }
    else if (this.data.input_key !== "") {     
      //历史记录写入缓存和获取
      var array = that.data.history;
      if (array.length < 8 && array.length > 0) {
        
        // 判断数组中是否已存在
        var newArr = array.findIndex(function (item) {
          return item.name === that.data.input_key;
        });
        console.log(newArr);
        if (newArr != -1) {
          // 删除已存在后重新插入至数组
          array.splice(newArr, 1)
          array.unshift({ name: that.data.input_key })
        } else {
          array.unshift({ name: that.data.input_key })
        }
      } else if (array.length =0){
        array.unshift({ name: that.data.input_key })
      }
      else {
        array.pop()//删掉旧的时间最早的第一条
        array.unshift({ name: that.data.input_key })
      }
      wx.setStorageSync('lishi', array);
      that.getHistory();
    }
  },
  //清除文本框的value
  clearInput:function(){
    var that = this;
    that.setData({
      input_key : ""
    })   
  },
  //历史记录获取缓存
  getHistory:function(){
    var that=this;
    wx.getStorage({
      key: "lishi",
      success: function (res) {
        that.setData({
          history: res.data
        })
      }
    })
  },
 //清除历史记录
  remove:function(e){
    var that = this;
    wx.removeStorageSync('lishi')
    that.setData({
      history: [],
    })
  },
  //点击历史记录中的标签,搜索
  historyJiLu:function(e){
    var that = this;
    that.setData({
      input_key: e.currentTarget.dataset.id
    })
    this.Load();
  },
  onLoad: function (options) {
    this.getHistory();
  },
})
  
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值