首页 > 解决方案 > 如何制作一个搜索列表,其中仅在用户搜索其确切值时才显示该元素

问题描述

所以,我有这个 html 代码来显示一个数字列表:

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="search">

<ul id="myUL">
  <li><a href="#">006372145</a></li>
  <li><a href="#">00021030</a></li>

  <li><a href="#">9123981283</a></li>
  <li><a href="#">190238120983</a></li>

  <li><a href="#">128378</a></li>
  <li><a href="#">1298488</a></li>
  <li><a href="#">12983498</a></li>
</ul>

还有一个搜索栏,用户可以在其中输入文本。这是JS代码:

function myFunction() {
    // Declare variables
    var input, filter, ul, li, a, i;
    input = document.getElementById('myInput');
    filter = input.value.toUpperCase();
    ul = document.getElementById("myUL");
    li = ul.getElementsByTagName('li');

    if(input.value.length == 0){
        ul.style.display = "none";
        return;
    }else{
        ul.style.display = "block";
    }
    // Loop through all list items, and hide those who don't match the search query
    for (i = 0; i < li.length; i++) {
        a = li[i].getElementsByTagName("a")[0];
        if (a.innerHTML.toUpperCase().indexOf(filter) == 0) {
            li[i].style.display = "block";
        } 
        else {
            li[i].style.display = "none";
        }

    }
  }

它过滤搜索输入以最终匹配一个数字,但我试图让它只显示完全相同的数字而不过滤其余数字以查看是否有任何匹配。

例如,我输入“00”并且没有数字显示,因为它不在列表中。但是,如果我输入了与列表中显示的数字完全匹配的数字。

标签: javascripthtml

解决方案


function applyFilter(userInput){
    /*
      Use css to set the display to none first
    */
    var options = document.querySelectorAll("#myUL > a");
    for(var i = 0; i < options.length; i++){
        if(options[i].textContent.trim() == userInput.trim()){
            // You can also convert to lowercase for more accurate result
            options[i].style.display = "inline";
        }
    }
}


推荐阅读