使用 jQuery 鍵入過濾關鍵字搜尋列表檢視搜尋列表?
以下是我們的輸入型別,使用者將在其中進行搜尋 −
<input type="text" class="txtInput" id="searchTheKey" placeholder="Enter the keywords to search.....">
現在,使用 hide() 和 show() 僅顯示相關的搜尋並隱藏其餘搜尋。例如,在鍵入“Ja”時,應顯示以“Ja”開頭的相關關鍵字,如“Java”和“JavaScript”。
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<label>
Enter the keyword..
<input type="text" class="txtInput" id="searchTheKey" placeholder="Enter the keywords to search.....">
</label>
<ul id="matchKey">
<li id="subjectName">JavaScript</li>
<li id="teacherName"><a href="#">John Smith</a></li>
<li id="subjectName">Java</li>
<li id="teacherName"><a href="#">David Miller</a</li>
<li id="subjectName">MongoDB</li>
<li id="teacherName"><a href="#">Carol Taylor</a></li>
</ul>
<script>
$("#searchTheKey").on('keyup', function(){
var value = $(this).val().toLowerCase();
$("#matchKey li").each(function () {
if ($(this).text().toLowerCase().search(value) > -1) {
$(this).show();
$(this).prev('.subjectName').last().show();
} else {
$(this).hide();
}
});
})
</script>
</body>
</html>要執行上述程式,請儲存檔名 “anyName.html(index.html)” 並右鍵單擊該檔案。在 VS Code 編輯器中選擇“使用 Live Server 開啟”選項。
輸出
將產生以下輸出 −

現在,我僅輸入 Java 並得到搜尋結果。螢幕截圖如下 −

請看上面的快照,其餘的專案列表均已隱藏。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP