1. 程式人生 > >微信小程式_實現輸入框帶搜尋記錄功能

微信小程式_實現輸入框帶搜尋記錄功能

                                

wxml:

  <view class="menu">
    <input class='search' placeholder='輸入商品名稱' placeholder-class='pla' bindinput='input_txt' bindconfirm='btn_search' value='{{searchValue}}'></input>
    <button class='btn' bindtap='btn_search'>搜尋</button>
  </view>
  <view class='history' bindtap='deleteHistory' wx:if="{{showHistory}}">清除搜尋歷史</view>
  <view class='h_con' wx:if="{{showHistory}}">
    <view class='h_con1'>
      <view class="title" wx:for="{{history}}" bindtap='toSearch' data-value='{{item}}' data-index="{{index}}">{{item}}</view>
    </view>
  </view>

js:

var searchArray = []

  
input_txt: function(e) {//輸入框輸入事件
    that.setData({
      searchTxt: e.detail.value.trim()
    })
  },
  btn_search: function() {//搜尋確認事件
    if (that.data.searchTxt == "") {
      wx.showToast({
        title: '商品名不為空',
        image: '/images/error.png',
        duration: 1000
      })
      return;
    }
    that.buildHistory(that.data.searchTxt)//呼叫歷史記錄事件
  },
//建立搜尋記錄
  buildHistory: function(e) {
    if (wx.getStorageSync("history").length > 0 && wx.getStorageSync("history").length < 8) {//小於指定數量之內
      let index = wx.getStorageSync("history").indexOf(e)
      if (index < 0) {//資料不存在時直接追加
        searchArray = wx.getStorageSync("history").concat(e)
        wx.setStorageSync("history", searchArray)
      } else {//資料已存在時調到頭部
        searchArray = wx.getStorageSync("history")
        searchArray.splice(index, 1)
        searchArray = searchArray.concat(e);
        wx.setStorageSync("history", searchArray)
      }
    } else if (wx.getStorageSync("history").length >= 8) {//大於指定數量
      let index1 = wx.getStorageSync("history").indexOf(e)
      if (index1 > -1) {//資料已存在時掉到頭部
        searchArray = wx.getStorageSync("history")
        searchArray.splice(index1, 1)
        searchArray = searchArray.concat(e);
        wx.setStorageSync("history", searchArray)
        return;
      }
      //資料不存在時刪除第一個後追加
      searchArray = wx.getStorageSync("history")
      searchArray.splice(0, 1)
      searchArray = searchArray.concat(e);
      wx.setStorageSync("history", searchArray)
    } else {//無資料時候直接追加
      searchArray = searchArray.concat(e)
      wx.setStorageSync("history", searchArray)
    }
  },