我创建了一个嵌入在两个不同表中的过滤搜索列表。
我希望能够在表格的标题保留到位时检索我在搜索框中输入的饮品的结果。
例如,如果我输入单词“Corona”,我希望看到单词corona出现以及Spirits的标题,即使该类别下没有匹配的单词。
我不知道我做错了什么
* {
box-sizing: border-box;
}
#myInput {
width: 40%;
font-size: 16px;
padding: 12px 20px 12px 40px;
border: 1px solid #ddd;
border-radius:7px;
margin-bottom: 12px;
margin-left:45px;
}
#myUL {
list-style-type: none;
padding: 0;
margin-left:45px;
display: block;
}
#myUL li a {
border: 1px solid #ddd;
border-radius:7px;
margin-top: -1px; /* Prevent double borders */
width:30%;
padding: 8px;
text-decoration: none;
font-size: 18px;
color: black;
background-color:#f6f6f6;
display: block;
}
.t1 {
float:left;
background:yellow;
margin-left:10px;
}
.t2 {
float:left;
background:cyan;
margin-left:50px;
}
li {list-style-type: none;}
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Ingresa palabra a buscar" title="Ejemplo: Cuenta NT">
</br>
<table class="t1">
<tr>
<th>SPIRITS</th>
</tr>
<ul id="myUL">
<tr><li><td>Armagnac</td></li></tr>
<tr><li><td>Gin</td></li>
<tr><li><td>Vodka</td></li></tr>
</table>
<table class="t2">
<tr>
<th>BEERS</th>
</tr>
<tr><td><li>Budweiser</li></td></tr>
<tr><td><li>Corona</li></td></tr>
<tr><td><li>Heineken</li></td></tr>
</ul>
</table>
<script>
function myFunction() {
var input, filter, ul, li, a, i,;
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];
if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}
</script>
答案 0 :(得分:0)
我重新编写代码,看看它是否对您有所帮助。
var filter = document.getElementById('myInput');
var drinks = document.querySelectorAll('.drink-name');
filter.addEventListener('keyup',function(e){
var s = e.target.value.toLowerCase();
drinks.forEach(function(el,i){
if(s.length > 2){
if(el.textContent.toLowerCase().indexOf(s) < 0){
el.style.display = 'none';
}else{
el.style.display = 'block';
}
}else{
drinks.forEach(function(el,i){
el.style.display = 'block';
});
}
});
});
#myInput{
padding: 10px;
border-radius: 5px;
font-size: 14px;
border: 1px solid #CCC;
}
.list{
float: left;
padding: 10px;
margin-right: 20px;
list-style: none;
}
.list li:nth-child(1){
font-weight: bold;
margin-bottom: 5px;
}
#list1{
background: yellow;
}
#list2{
background: cyan;
}
<input type="text" id="myInput" placeholder="Ingresa palabra a buscar">
<br>
<ul id="list1" class="list">
<li>SPIRITS</li>
<li class="drink-name">Armagnac</li>
<li class="drink-name">Gin</li>
<li class="drink-name">Vodka</li>
</ul>
<ul id="list2" class="list">
<li>BEERS</li>
<li class="drink-name">Budweiser</li>
<li class="drink-name">Corona</li>
<li class="drink-name">Heineken</li>
</ul>