如何使用 JavaScript 创建过滤列表?
javascriptweb developmentobject oriented programming
使用 JavaScript 创建过滤列表,代码如下 −
示例
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style> * { box-sizing: border-box; } .searchInput { width: 100%; font-size: 16px; padding: 12px 20px 12px 40px; border: 2px solid grey; margin-bottom: 12px; } .animalUL { list-style-type: none; padding: 0; margin: 0; } .animalUL li a { border-top: 1px solid rgb(0, 0, 0); margin-top: -1px; background-color: #f6f6f6; padding: 12px; text-decoration: none; font-size: 18px; color: black; display: block; } .animalUL li a:hover:not(.header) { background-color: #eee; } </style> </head> <body> <h1>Filter list example</h1> <input type="text" class="searchInput" onkeyup="filterFunction()" placeholder="Search for animals" title="Type in a name"/> <ul class="animalUL"> <li><a href="#">Cat</a></li> <li><a href="#">Cheetah</a></li> <li><a href="#">Dog</a></li> <li><a href="#">Giraffe</a></li> <li><a href="#">Lion</a></li> <li><a href="#">Leopard</a></li> <li><a href="#">llama</a></li> </ul> <script> function filterFunction() { var input, filter, ul, li, a, i, value; input = document.querySelector(".searchInput"); filter = input.value.toUpperCase(); ul = document.querySelector(".animalUL"); li = ul.getElementsByTagName("li"); for (i = 0; i < li.length; i++) { a = li[i].getElementsByTagName("a")[0]; value = a.textContent || a.innerText; if (value.toUpperCase().indexOf(filter) > -1) { li[i].style.display = ""; } else { li[i].style.display = "none"; } } } </script> </body> </html>
输出
上述代码将产生以下输出 −
在搜索栏中输入内容时 −