前端实时搜索框模拟

此demo模拟一个页面实时搜索功能,仅在前端利用js交互,实际使用效果并不理想。

若想实现更复杂的实时搜索功能(包含前后台交互),

推荐使用BootStrap中的Select2组件。可参考本人另一篇博客:BootStrap之select2使用心得

<html><head><title>实时查询</title>

<style>
label:before
{
content:"*";
color:red;
font-size:120%;
vertical-align:middle;
}

</style>
</head>
<meta charset = "utf-8" >
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.1.min.js"></script>


<body>
<label for="searchCityName">查询</label>
<input id="searchCityName" style="width: 20%;" type="text" placeholder="中文 / 拼音首字母" /> 
<ul> 
<li pinyin="bj" cityname="北京"><a href="">北京 </a></li> 
<li pinyin="dl" cityname="大连"><a href="">大连 </a></li> 
<li pinyin="sh" cityname="上海"><a href="">上海 </a></li> 
<li pinyin="jn" cityname="济南"><a href="">济南 </a></li> 
<li pinyin="gz" cityname="广州"><a href="">广州 </a></li> 
<li pinyin="jh" cityname="金华"><a href="">金华 </a></li> 
<li pinyin="wh" cityname="武汉"><a href="">武汉 </a></li> 
<li pinyin="nj" cityname="南京"><a href="">南京 </a></li> 
<li pinyin="sz" cityname="深圳"><a href="">深圳 </a></li> 
<li pinyin="tj" cityname="天津"><a href="">天津 </a></li> 
<li pinyin="cd" cityname="成都"><a href="">成都 </a></li> 
<li pinyin="ly" cityname="临沂"><a href="">临沂 </a></li> 
<li pinyin="cc" cityname="长春"><a href="">长春 </a></li> 
<li pinyin="hz" cityname="杭州"><a href="">杭州 </a></li> 
<li pinyin="nb" cityname="宁波"><a href="">宁波 </a></li> 
<li pinyin="qd" cityname="青岛"><a href="">青岛 </a></li> 
<li pinyin="sy" cityname="沈阳"><a href="">沈阳 </a></li> 
</ul>
<script>
function searchCity() {
var searchCityName = $("#searchCityName").val();

if (searchCityName == "") {
$("ul li").show();
} else {
$("ul li").each( 
function() {
var pinyin = $(this).attr("pinyin"); 
var cityName = $(this).attr("cityName"); 
if (pinyin.indexOf(searchCityName) != -1 || cityName.indexOf(searchCityName) != -1) {
$(this).show();
} else {
$(this).hide();
}
});
}
}
$('#searchCityName').bind('input propertychange', function() {
searchCity();
}); 
</script>
</body>

</html>

 

 

<!-- <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.1.min.js"></script>
<title>输入监测</title>
<script type="text/javascript">
window.onload=function(){
var otxt=document.getElementById("txt");
var oshow=document.getElementById("show");
var count=0;
if(document.all){
otxt.onpropertychange=function(){
count=count+1;
oshow.innerHTML=count;
}
}
else{
otxt.oninput=function(){
count=count+1;
oshow.innerHTML=count;
}
}
}

$(function(){
$("input[type='search']").bind('input propertychange',function(){
//做一些事情
var val = $(this).val(); 
console.log(val);
alert(val);
})
});
</script>
</head>
<body>
<div id="show"></div>
<input type="text" id="txt" value="测试"/>
</body>
</html> -->

 

posted @ 2019-03-26 10:44  imOne  阅读(1989)  评论(0编辑  收藏  举报