1,监听输入框内容变化,获得输入框值
这边使用input的oninput属性,所以HTML代码这么写
<input id="search" placeholder="搜索" οninput="OnInput (event)">
<div id="list" >
</div>
js代码
function OnInput(event){
if( event.target.value==""){
$("list").hide();
}else{//提交搜索功能
go_to_search()
}
}
function go_to_search(){
$("#list").html("<br>");
$("#list").show();
//使用ajax 查询接口,返回值追加写入id为list的div中
}
到这似乎已经完成功能开发了,可是测试使用的就会发现有问题
1,中文拼音的时候,会还没打完,就提交搜索,会加大服务器压力
2,点到其他地方的时候需要把选择列表做隐藏,再点回搜索框再显示,才符合使用习惯
2,进阶版
(1)解决中文拼音输入问题
输入框绑定compositionstart和compositionend事件来监控输入法开始和结束事件
使用一个公共变量来记录是否搜索
var is_search=true;
$("#search").off().on({
compositionstart:function(){
is_search=false;
},
compositionend:function(){
is_search=true;
go_to_search();
}
})同时OnInput需要改成
function OnInput(event){
if( event.target.value==""){
$(list").hide();
}else{
if(is_search){//提交搜索功能
go_to_search()
}
}
}
(2)显示隐藏问题
这边使用一个取巧的办法,大概思路就是,body绑定隐藏的事件,点击输入框和列表增加一个阻止隐藏的变量;
html代码,输入框绑定onFocus事件
<input id="search" placeholder="搜索" onFocus="InInput(event)" οninput="OnInput (event)">
js代码
var is_hide=1;
$("body").click(function (){
if(is_hide==1){
$("#list").hide();
}else{//很重要
is_hide=1;
}
})
$("#list").click(function (){
is_hide=0;
})
function InInput(event){
is_hide=0;
if( event.target.value==""){
$("#list").hide();
}else{
$("#list").show();
}
}
最后代码
HTML
<input id="search" placeholder="搜索" onFocus="InInput(event)" οninput="OnInput (event)">
<div id="list" >
</div>
JS
var is_search=true;
var is_hide=1;
$("#search").off().on({
compositionstart:function(){
is_search=false;
},
compositionend:function(){
is_search=true;
go_to_search();
}
})function OnInput(event){
if( event.target.value==""){
$(list").hide();
}else{
if(is_search){//提交搜索功能
go_to_search()
}
}
}$("body").click(function (){
if(is_hide==1){
$("#list").hide();
}else{//很重要
is_hide=1;
}
})
$("#list").click(function (){
is_hide=0;
})
function InInput(event){
is_hide=0;
if( event.target.value==""){
$("#list").hide();
}else{
$("#list").show();
}
}
如若有误或者有其他问题请与我交流:2359582968(微信qq同号)