日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

小程序搜索框歷史記錄,去除重復(fù)搜索內(nèi)容,限制顯示條數(shù)

作者:Zan^Z 更新時(shí)間: 2022-02-15 編程語言

在這里插入圖片描述
以上為搜索界面

小程序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頁面
歷史記錄是先把獲取到的數(shù)據(jù),加入緩存,再取到緩存中的數(shù)據(jù),加到wxml需要用到的數(shù)組里,再判斷數(shù)組中是否已存在時(shí),最開始使用indexOf,但是返回值一直都是-1,解決方法和疑問在下一個(gè)文檔里

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) {
        
        // 判斷數(shù)組中是否已存在
        var newArr = array.findIndex(function (item) {
          return item.name === that.data.input_key;
        });
        console.log(newArr);
        if (newArr != -1) {
          // 刪除已存在后重新插入至數(shù)組
          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()//刪掉舊的時(shí)間最早的第一條
        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: [],
    })
  },
  //點(diǎn)擊歷史記錄中的標(biāo)簽,搜索
  historyJiLu:function(e){
    var that = this;
    that.setData({
      input_key: e.currentTarget.dataset.id
    })
    this.Load();
  },
  onLoad: function (options) {
    this.getHistory();
  },
})
  

原文鏈接:https://blog.csdn.net/Zan_Z/article/details/104984832

欄目分類
最近更新