小编the*_*ode的帖子

For循环无法使用Array。如何解决?

我想在网站上创建搜索栏。键入时,它应该会更新内容。使用if语句,它可以正常工作。但是for循环会导致问题。

var shoplist = ["1", "2", "3"];
var shoplistlength

function hid(event) {
  event.preventDefault();
  shopsuche = document.getElementById("search").value;

  for (var i = 0; i < shoplistlength; i++) {
    if (shoplist[i].includes(shopsuche)) {
      document.getElementById("2").children[i].style.display = "inline"
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

输入字段:

<input class="form-control mr-sm-2"
                    type="search"
                    placeholder="What you are looking for?"
                    aria-label="Search"
                    name="search"
                    id="search"
                    onkeyup="hid(event)"
                    >
Run Code Online (Sandbox Code Playgroud)

我想通过for循环最小化代码。我将检查商店列表中的每个变量,然后检查商店是否包含列表中的字母。如果是,则该站点应显示一个列表元素。我将获得带有变量i的ul列表子级,因为商店列表的构建类似于列表。

更新:

我删除了shoplistLength并将其替换为数字。我知道这不是最好的方法,但是我尝试理解我的错误。我认为我的阵列有问题。如果我这样做:

 var shoplist = ["1", "2", "3"];
 function hid(event){
 ... 
 for (var i = 0; i < 3; i++){
     if ("1".includes(shopsuche)) { 
       document.getElementById("2").children[i].style.display="none"} 
Run Code Online (Sandbox Code Playgroud)

我得到了预期的结果。但是,如果我使用数组和索引:

if (shoplist[i].includes(shopsuche)) { 
Run Code Online (Sandbox Code Playgroud)

那么该站点保持不变。

javascript for-loop searchbar

0
推荐指数
1
解决办法
81
查看次数

标签 统计

for-loop ×1

javascript ×1

searchbar ×1