如何過濾/搜索列表
學習如何使用 JavaScript 創建過濾列表。
過濾列表
如何使用 JavaScript 搜索列表中的項目。
創建搜索列表
第一步 - 添加 HTML:
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.."> <ul id="myUL"> <li><a href="#">Adele</a></li> <li><a href="#">Agnes</a></li> <li><a href="#">Billy</a></li> <li><a href="#">Bob</a></li> <li><a href="#">Calvin</a></li> <li><a href="#">Christina</a></li> <li><a href="#">Cindy</a></li> </ul>
注意:在此演示中,我們使用 href="#",因為我們沒有頁面可以鏈接到。在實際應用中,這應該是指向特定頁面的真實 URL。
第二步 - 添加 CSS:
設置輸入元素和列表的樣式:
#myInput { background-image: url('/css/searchicon.png'); /* 向輸入框添加搜索圖標 */ background-position: 10px 12px; /* 定位搜索圖標 */ background-repeat: no-repeat; /* 不要重復圖標圖像 */ width: 100%; /* 全寬 */ font-size: 16px; /* 增加字體大小 */ padding: 12px 20px 12px 40px; /* 添加一些內邊距 */ border: 1px solid #ddd; /* 添加灰色邊框 */ margin-bottom: 12px; /* 在輸入框下方添加一些空間 */ } #myUL { /* 移除默認的列表樣式 */ list-style-type: none; padding: 0; margin: 0; } #myUL li a { border: 1px solid #ddd; /* 為所有鏈接添加邊框 */ margin-top: -1px; /* 防止雙邊框 */ background-color: #f6f6f6; /* 灰色背景色 */ padding: 12px; /* 添加一些內邊距 */ text-decoration: none; /* 移除默認文本下劃線 */ font-size: 18px; /* 增加字體大小 */ color: black; /* 添加黑色文本顏色 */ display: block; /* 使其成為塊級元素以填充整個列表 */ } #myUL li a:hover:not(.header) { background-color: #eee; /* 為所有鏈接(除了標題)添加懸停效果 */ }
第三步 - 添加 JavaScript:
<script> function myFunction() { // Declare variables var input, filter, ul, li, a, i, txtValue; input = document.getElementById('myInput'); filter = input.value.toUpperCase(); ul = document.getElementById("myUL"); li = ul.getElementsByTagName('li'); // 遍歷所有列表項,并隱藏那些與搜索查詢不匹配的項 for (i = 0; i < li.length; i++) { a = li[i].getElementsByTagName("a")[0]; txtValue = a.textContent || a.innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { li[i].style.display = ""; } else { li[i].style.display = "none"; } } } </script>
提示:如果要執行區分大小寫的搜索,請刪除 toUpperCase()。
相關頁面
教程:如何過濾/搜索表格