1. 程式人生 > 實用技巧 >js實時查詢,為空提示

js實時查詢,為空提示

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=width-width, initial-scale=1, minimum-scale=1, maximum-scale=1"/>
    <title>實時查詢</title>
    <script src="../commonJs/jquery-3.1.0.min.js"></script
> <style> * { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; margin: 0; padding: 0; } body { padding-top: 30px; margin: 0 auto; } ul
{ width: 80%; margin: 10px auto 0; list-style: none; } input { display: block; width: 80%; padding: 5px; margin: 0 auto; outline: none; } p { display: none; text-align
: center; } </style> </head> <body> <input type="text" id="searchInput" placeholder="請輸入查詢資訊"/> <ul> <li>A. you can <small>2020-09-10</small></li> <li>B. you must can <small>星期四</small></li> <li>C. try your best <small>下午,雨天</small></li> <li>D. live your life without regret <small>工作記錄</small></li> </ul> <p>沒有查詢結果</p> <script> $(function() { $("#searchInput").keyup(function() { var value = $(this).val(); // 獲取搜尋框的內容 var flag = true; // 控制為空提示 $("ul li").each(function() { // 對查詢各個選項進行遍歷 $(this).hide(); // 將各個選項設定隱藏 // $(this).text()獲取專案<li>的文字,呼叫indexOf(),$.trim(value)去掉輸入內容的左右空格,如何匹配,則顯示相應選項,匹配不到結果為-1,條件等於0也成立是因為內容框沒有結果時把選項都顯示。 if ($(this).text().indexOf($.trim(value)) >= 0) { $("p").hide(); // 若出現查詢結果為空時,為空提示會顯示,再次搜尋到相應選項時,為空提示應該隱藏。 $(this).show(); // 根據搜尋內容匹配選項,將選項顯示 flag = false; // 改變為空控制條件,使得有選項符合查詢條件不顯示為空提示。 } }); if(flag) { $("p").show(); } }); }) </script> </body> </html>

———— 就多嘗試吧~求知精神會豐富你暫時空白的腦殼子的————