前端實時搜尋框模擬

imOne發表於2019-03-26

此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> -->

 

相關文章