小程序input联想输入

转自:https://www.jianshu.com/p/3f40578cb94b

欢迎关注本人公众号和小程序

wxml

<view>
  <input class="textinput" bindinput="bindinput" value="{{inputValue}}" placeholder="请输入内容" />
</view>

<scroll-view scroll-y="true" class="scrollview" hidden="{{hideScroll}}" style="{{arrayHeight>340?'height:340rpx':''}}">
  <view wx:for="{{bindSource}}">
    <view id="{{item}}" bindtap="itemtap" class="itemview">{{item}}</view>
  </view>
</scroll-view>

js

var wayIndex = -1;
var school_area = '';
var grade = '';
// 当联想词数量较多,使列表高度超过340rpx,那设置style的height属性为340rpx,小于340rpx的不设置height,由联想词列表自身填充
// 结合上面wxml的<scroll-view>
var arrayHeight = 0;

Page({
  data: {
    inputValue: '', //点击结果项之后替换到文本框的值
    adapterSource: ["weixin", "wechat", "android", "Android", "IOS", "java", "javascript", "微信小程序", "微信公众号", "微信开发者工具"], //本地匹配源
    bindSource: [], //绑定到页面的数据,根据用户输入动态变化
    hideScroll: true,
  },
  
  //当键盘输入时,触发input事件
  bindinput: function (e) {
    //用户实时输入值
    var prefix = e.detail.value
    //匹配的结果
    var newSource = []
    if (prefix != "") { 
      // 对于数组array进行遍历,功能函数中的参数 `e`就是遍历时的数组元素值。
      this.data.adapterSource.forEach(function (e) { 
        // 用户输入的字符串如果在数组中某个元素中出现,将该元素存到newSource中
        if (e.indexOf(prefix) != -1) {
          console.log(e);
          newSource.push(e)
        }
      })
    };
    // 如果匹配结果存在,那么将其返回,相反则返回空数组
    if (newSource.length != 0) {
      this.setData({
        // 匹配结果存在,显示自动联想词下拉列表
        hideScroll: false,
        bindSource: newSource,
        arrayHeight: newSource.length * 71
      })
    } else {
      this.setData({
        // 匹配无结果,不现实下拉列表
        hideScroll: true,
        bindSource: []
      })
    }
  },

  // 用户点击选择某个联想字符串时,获取该联想词,并清空提醒联想词数组
  itemtap: function (e) {
    this.setData({
      // .id在wxml中被赋值为{{item}},即当前遍历的元素值
      inputValue: e.target.id,
      // 当用户选择某个联想词,隐藏下拉列表
      hideScroll: true,
      bindSource: []
    })
  },
})

如何在input里添加多个候选值呢?请看下篇小程序input联想输入,可输入多个侯选值

猜你喜欢

转载自blog.csdn.net/haohaizijhz/article/details/89951284
今日推荐