Input事件在输入法输入时也会触发并更新value,当我们使用输入法时,input也会触发,
向百度这样,
但在在我们做搜索过滤的时候往往希望等汉字收入完成以后再进行搜索,所以我们就不能简简单单的使用input事件,需要进行小小的优化,上代码
function formatInput(id, callBack) {
var target = document.getElementById(id);
target.inputMethod = false;
target.addEventListener('compositionstart', function(){
this.inputMethod = true;
});
target.addEventListener('compositionend', function(){
this.inputMethod = false;
callBack(this.value)
});
target.addEventListener('input', function(){
if(!this.inputMethod){
callBack(this.value)
}
});
}
传入input标签的id,并你定一个回调,在回调中返回input的value值,
<input id="test" class="search-page_input" type="text" placeholder="请输入">
测试样例
formatInput("test", log);
function log(res) {
console.log(res);
// 请求服务器操作
}