我想在网站上创建一个搜索栏。它应该在您打字时更新内容。使用 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"
}
}
}
输入字段:
<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)"
>
我想通过for循环最小化代码。我将检查商店列表中的每个变量,然后检查 shopsuche 是否包含列表中的字母。如果是,则该站点应显示一个列表元素。我将使用变量 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"}
我得到了预期的结果。但是,如果我使用数组和索引:
if (shoplist[i].includes(shopsuche)) {
然后网站保持不变。
最佳答案
看起来您没有实例化 shopListLength
任何东西,所以你的循环说 for(var i = 0; i < undefined; i++)
这将立即退出。
关于javascript - For 数组上的循环不起作用。如何修复它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57528895/