本文實例講述了jQuery簡單實現的HTML頁面文本框模糊匹配查詢功能。分享給大家供大家參考,具體如下:
項目中需要用到此功能,使用過EasyUI中的Combobox,網上也搜過相應的解決辦法,對于我的項目來說都不太合適,因為我還是喜歡比較純粹的東西,就自己動手寫了一個,比較簡單,但還算能用,我的項目中也已經使用上了,做了個小demo作為記錄,有需要的自己復制代碼改一改就好了。
使用在線HTML/css/JavaScript運行工具:http://tools.VeVB.COm/code/HtmlJsRun 運行代碼,可看到如下效果展示圖:
接下來是代碼,純html+css+jquery的:
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> <title>www.49028c.com jQuery模糊匹配查詢</title> <style type="text/css"> #div_main { margin: 0 auto; width: 300px; height: 400px; border: 1px solid black; margin-top: 50px; } #div_txt { position: relative; width: 200px; margin: 0 auto; margin-top: 40px; } #txt1 { width: 99%; } #div_items { position: relative; width: 100%; height: 200px; border: 1px solid #66afe9; border-top: 0px; overflow: auto; display: none; } .div_item { width: 100%; height: 20px; margin-top: 1px; font-size: 13px; line-height: 20px; } </style></head><body> <div id="div_main"> <!--表單的autocomplete="off"屬性設置可以阻止瀏覽器默認的提示框--> <form autocomplete="off"> <div id="div_txt"> <!--要模糊匹配的文本框--> <input type="text" id="txt1" /> <!--模糊匹配窗口--> <div id="div_items"> <div class="div_item">周杰倫</div> <div class="div_item">周杰</div> <div class="div_item">林俊杰</div> <div class="div_item">林宥嘉</div> <div class="div_item">林妙可</div> <div class="div_item">唐嫣</div> <div class="div_item">唐家三少</div> <div class="div_item">唐朝盛世</div> <div class="div_item">奧迪A4L</div> <div class="div_item">奧迪A6L</div> <div class="div_item">奧迪A8L</div> <div class="div_item">奧迪R8</div> <div class="div_item">寶馬GT</div> </div> </div> </form> </div></body></html><script type="text/javascript"> //彈出列表框 $("#txt1").click(function () { $("#div_items").css('display', 'block'); return false; }); //隱藏列表框 $("body").click(function () { $("#div_items").css('display', 'none'); }); //移入移出效果 $(".div_item").hover(function () { $(this).css('background-color', '#1C86EE').css('color', 'white'); }, function () { $(this).css('background-color', 'white').css('color', 'black'); }); //文本框輸入 $("#txt1").keyup(function () { $("#div_items").css('display', 'block');//只要輸入就顯示列表框 if ($("#txt1").val().length <= 0) { $(".div_item").css('display', 'block');//如果什么都沒填,跳出,保持全部顯示狀態 return; } $(".div_item").css('display', 'none');//如果填了,先將所有的選項隱藏 for (var i = 0; i < $(".div_item").length; i++) { //模糊匹配,將所有匹配項顯示 if ($(".div_item").eq(i).text().substr(0, $("#txt1").val().length) == $("#txt1").val()) { $(".div_item").eq(i).css('display', 'block'); } } }); //項點擊 $(".div_item").click(function () { $("#txt1").val($(this).text()); });</script>
更多關于jQuery相關內容感興趣的讀者可查看本站專題:《jQuery表格(table)操作技巧匯總》、《jQuery切換特效與技巧總結》、《jQuery擴展技巧總結》、《jQuery常用插件及用法總結》、《jQuery拖拽特效與技巧總結》、《jquery中Ajax用法總結》、《jQuery常見經典特效匯總》、《jQuery動畫與特效用法總結》及《jquery選擇器用法總結》
希望本文所述對大家jQuery程序設計有所幫助。
新聞熱點
疑難解答