只有在调用函数时才能使下拉列表可见

时间:2017-11-07 19:53:45

标签: javascript html css

我正在尝试仅在搜索栏中输入内容时才显示下拉列表。否则它将保持折叠状态。以下是我的代码

function mysearchFunction() {
  var input, upperCase, ul, li, x, i, ax;
  input = document.getElementById("mysearchInput");
  upperCase = input.value.toUpperCase();
  ul = document.getElementById("myList");
  li = ul.getElementsByTagName("li");
  for (i = 0; i < li.length; i++) {
    x = li[i].getElementsByTagName("a")[0];
    if (x.innerHTML.toUpperCase().indexOf(upperCase) === 0) {
      li[i].style.visibility = "visible";
      li[i].style.display = "block";
    } else {
      li[i].style.display = "none";
    }
  }
}
#myList li a {
  border: 1px solid #ddd;
  margin-top: -2px;
  background-color: #f6f6f6;
  padding: 10px;
  text-decoration: none;
  font-size: 16px;
  color: black;
  display: block;
  visibility: collapse;
}
<input type="text" id="mysearchInput" onkeyup="mysearchFunction()" placeholder="Search..">
<ul id="myList">
  <li><a href="#">America</a></li>
  <li><a href="#">Africa</a></li>
  <li><a href="#">Antartica</a></li>
  <li><a href="#">Asia</a></li>
  <li><a href="#">Europe</a></li>
  <li><a href="#">Australia</a></li>
</ul>

在JS中,我试图只制作需要显示为可见的内容。请指导我哪里出错了。目前没有显示任何内容。它正在崩溃。

1 个答案:

答案 0 :(得分:0)

刚刚更新了css选择器:#myList li,您隐藏了所有链接。

function mysearchFunction() {
  var input, upperCase, ul, li, x, i, ax;
  input = document.getElementById("mysearchInput");
  upperCase = input.value.toUpperCase();
  //console.log(upperCase);
  ul = document.getElementById("myList");
  li = ul.getElementsByTagName("li");
  for (i = 0; i < li.length; i++) {
    x = li[i].getElementsByTagName("a")[0];
    if (x.innerHTML.toUpperCase().indexOf(upperCase) == 0 && upperCase !== '') {
      li[i].style.visibility = "visible";
      li[i].style.display = "block";
    } else {
      li[i].style.display = "none";
    }
  }
}
#myList li {
  border: 1px solid #ddd;
  margin-top: -2px;
  background-color: #f6f6f6;
  padding: 10px;
  text-decoration: none;
  font-size: 16px;
  color: black;
  display: block;
  visibility: collapse;
}
<input type="text" id="mysearchInput" onkeyup="mysearchFunction()" placeholder="Search..">
<ul id="myList">
  <li><a href="#">America</a></li>
  <li><a href="#">Africa</a></li>
  <li><a href="#">Antartica</a></li>
  <li><a href="#">Asia</a></li>
  <li><a href="#">Europe</a></li>
  <li><a href="#">Australia</a></li>
</ul>