简单页面搜索的代码问题 | 您所在的位置:网站首页 › 搜索页面的代码 › 简单页面搜索的代码问题 |
因为您有多个产品容器,所以使用document.getElementsByClassName()而不是document.getElementById(),并提供产品容器类作为参数。 let searchInput = document.getElementsByClassName ('container');您需要修改searchPage()方法。不要使用document来查找searchValue和parent,而要使用this。 let searchValue = this.getElementsByClassName('searchInput')[0].value; let parent = this.getElementsByClassName('container')[0];请添加HTML代码。 编辑:如果我理解正确的话,你有一个搜索输入,它将搜索多个产品容器。这里有一个简单的示例,您可以很容易地将其应用于您的问题。 HTML: KiwiKiwi description BananaBanana description AppleApple description JS: let searchInput = document.getElementById ('searchInput'); searchInput.addEventListener ('keyup', searchPage); function searchPage(){ let searchValue = this.value.toUpperCase(); let products = document.getElementsByClassName('product'); for(let i = 0; i < products.length; i++) { console.log(products[i].innerHTML.toUpperCase()); if (products[i].innerHTML.toUpperCase().indexOf(searchValue) > -1) products[i].parentNode.style.display = ''; else products[i].parentNode.style.display = 'none'; }; };CSS: .product-container { display: flex; flex-direction: column; margin-bottom: 10px; background: grey; } .product-container span { font-size: 20px; } .product { display: block; }https://jsfiddle.net/gardelin/koc5eg6v/25/ |
CopyRight 2018-2019 实验室设备网 版权所有 |