Jquery简单实现前端搜索功能
如果html页有很长的列表,我们自然想到了需要检索展示功能,本文用简单的方式实现了检索功能,首先是搜索的列表如下
<div id="show"> <div class="item">itemA</div> <div class="item">itemB</div> <div class="item">itemC</div> <div class="item">itemD</div> <div class="item">itemE</div> <div class="item">.......</div> <div class="item">itemZ</div> <div>
功能要求:输入关键词D,检索出内容列表,比如输入E,检索出:
<div id="show"> <div class="item">itemE</div> <div>
输入空,检索出所有的内容
用一个隐藏的副本做为搜索源,内容如下:
<div id="hidden" style="display:none"> <div class="item">itemA</div> <div class="item">itemB</div> <div class="item">itemC</div> <div class="item">itemD</div> <div class="item">itemE</div> <div class="item">.......</div> <div class="item">itemZ</div> <div>
引入JQuery可以方便我们搜索,设定一个搜索的input
<input type="text" placeholder="搜索内容.." onkeyup="return searchKeyPress(window.event)" id="search-text">
添加搜索的JS
function searchKeyPress(e){ var keynum = window.event ? e.keyCode : e.which; if(13 == keynum || (keynum >= 65 && keynum <=90) || (keynum >= 97 && keynum <=122) || 8 == keynum){ searchDomain(); } } function searchDomain() { var searchText = $("#search-text").val(); if(searchText != "" && searchText != null){ var html = ""; searchText = searchText.toLowerCase(); $("#hidden .item").each(function(){ var dataVal = $(this).text(); dataVal = dataVal.toLowerCase(); if(dataVal.indexOf(searchText) > -1){ html = html + "<div class='item'>" + $(this).html() + "</div>"; } }) if(html != ""){ $("#show").html(html); } } else { $("#show").html($("#hidden").html()); } }
记得用toLowerCase(),这样可以大小写模糊匹配,另外获取div内容的时候,用JQuery选择器不能获取整个html的内容,只能用这种本方法来拼接div了,html = html + "<div class='item'>" + $(this).html() + "</div>";
相关推荐
EdwardSiCong 2020-11-23
85477104 2020-11-17
hhanbj 2020-11-17
81427005 2020-11-11
seoppt 2020-09-13
honeyth 2020-09-13
WRITEFORSHARE 2020-09-13
84483065 2020-09-11
momode 2020-09-11
85477104 2020-08-15
83510998 2020-08-08
82550495 2020-08-03
tthappyer 2020-08-03
84901334 2020-07-28
tthappyer 2020-07-25
TONIYH 2020-07-22
tztzyzyz 2020-07-20
83510998 2020-07-18
81463166 2020-07-17