我正在尝试创建一个搜索/过滤功能,在这个功能中,只要搜索框中没有输入任何内容,选项列表就会被隐藏。我以前曾设法将其隐藏,但由于某种原因,在输入一个值并将其删除后,列表中的所有内容都会再次显示。
搜索还应该能够搜索出无序的单词,并且不能为了实现这一目标而牺牲这些单词。
代码复制如下。谢谢
CSS
#input {
width: 85%; /* Full-width */
padding: 12px 20px 12px 15px; /* Add some padding */
border: 1px solid #ddd; /* Add a grey border */
margin-bottom: 12px; /* Add some space below the input */
border-radius: 15px;
font-size: 16px;
font-family: Franklin Gothic Book;
}
#trpUL {
/* Remove default list styling */
list-style-type: none;
padding: 0;
margin: 0;
position: absolute;
z-index: 1;
width: 35%;
}
#trpUL li a {
border: 1px solid #ddd; /* Add a border to all links */
margin-top: -1px; /* Prevent double borders */
background-color: #f6f6f6; /* Grey background color */
padding: 12px; /* Add some padding */
text-decoration: none; /* Remove default text underline */
font-size: 13px; /* Increase the font-size */
font-weight: bold;
color: #1d4f91; /* Add a black text color */
display: block; /* Make it into a block element to fill the whole list */
font-family: Franklin Gothic Book;
}
#trpUL li {
display:none;
}
#trpUL li a:hover:not(.header) {
background-color: #eee; /* Add a hover effect to all links, except for headers */
}
javascript
function myFunction() {
var filter = $('input').val().toUpperCase().split(' ');
var li = $('li');
var a = $('a');
var ul;
var txtValue;
ul = document.getElementById("trpUL");
var match
for (var i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
txtValue = (a.textContent || a.innerText).toUpperCase();
match = true;
for (var f = 0; f < filter.length && match; f++) {
match = txtValue.includes(filter[f]);
}
li[i].style.display = match ? 'block' : 'none';
}
}
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input" onkeyup="myFunction()" placeholder="Search resources..." value="">
<ul id="trpUL">
<li><a href="/" target="_blank">Alabama HomeCare - New Hire Curriculum</a></li>
<li><a href="/" target="_blank">Arizona HomeCare - New Hire Curriculum</a></li>
<li><a href="/" target="_blank">California HomeCare Leadership - New Hire Curriculum</a></li>
<li><a href="/" target="_blank">Georgia HomeCare - New Hire Curriculum</a></li>
<li><a href="/" target="_blank">Georgia HomeCare IDD - New Hire Curriculum</a></li>
<li><a href="/" target="_blank">HomeCare Leadership - New Hire Curriculum</a></li>
<li><a href="/" target="_blank">Idaho HomeCare - New Hire Curriculum</a></li>
<li><a href="/" target="_blank">Illinois Licensed HomeCare - New Hire Curriculum</a></li>
<li><a href="/" target="_blank">Illinois Non-Licensed HomeCare</a></li>
<li><a href="/" target="_blank">Montana HomeCare - New Hire Curriculum</a></li>
</ul>