微信小程序input搜索解决中文问题(输入拼音) & 实时搜索节流处理(bindinput 节流)
问题
微信小程序输入拼音的时候, 还没有完全输入完成, bindinput就会触发, 当我输入"ni’hao", 还没有选定汉字"你好", 就已经触发了, 我想改成当选定"你好"后再触发
解决方案
bindinput 的detail中有一个 cursor 的属性,返回光标位置,可以根据 此次输入时的cursor对比上一次的cursor 来判断, 键盘输入时触发,event.detail = {value, cursor, keyCode}
Page({/*** 页面的初始数据*/data: {searchValue: '',cursor: 0}, inputOnchange: function(e) { if(e.detail.cursor != this.data.cursor) { this.setData({ cursor: e.detail.cursor, searchValue: e.detail.value }) console.log('确定输入内容' + this.data.searchValue) // 假设现在需要检测到用户输入的值,用户 500 毫秒内没有继续输入就将该值打印出来 this.throttle(this.queryData, null, 500, this.data.searchValue); } else { console.log('输入拼音名没有确定输入内容, 不搜索') } }, // 节流 throttle: function (fn, context, delay, text) { clearTimeout(fn.timeoutId); fn.timeoutId = setTimeout(function () { fn.call(context, text); }, delay); }, // 此处方法里面调用查询接口 queryData: function (e) { console.log(e) // 打印 用户输入的值 // // TODO 此处请求接口 // },})WXML
input class='search_input' maxlength='35' placeholder="输入关键词搜索"bindinput='inputOnchange'value='{{searchValue}}'bindconfirm='searchBtnClick' confirm-type='search' /














