我创建了一个自定义的JS搜索过滤器。要逐个字母搜索标记名'h2‘。例如:<h2>CHOCOLATE MOUSSE</h2>
、<h2>SMOKED LAMB WITH RICE</h2>
当在搜索栏上输入"mo“时,"display = block”。当输入"mou“时,第一个是"display = block",第二个是"display = none";
这是我的HTML代码。
<!DOCTYPE html>
<html>
<head>
<link href='style.css' rel='stylesheet' type='text/css'/>
<script src="./chat.js"></script>
</head>
<body>
<div class="col">
<div id="search-box">
<input type="text" placeholder="Search" class="input">
</div>
</div>
<main>
<div class="recipe a">
<h2>CHOCOLATE MOUSSE</h2>
<p class="description">
This delicious chocolate mousse will delight dinner guests of all ages!</p>
</div>
<div class="recipe b">
<h2>SMOKED LAMB WITH RICE</h2>
<p class="description">
Want to feel like your favorite relative came over and made you dinner? This comfort meal of smoked lamb and rice will quickly become a weekend favorite!
</p>
</div>
<div class="recipe c">
<h2>GOAT CHEESE SALAD</h2>
<p class="description">
In addition to the full flavor of goat cheese, this salad includes kale, avocado, and farro to balance it out.</p>
</div>
</main>
下面是我的javascript函数
const searchBar = document.forms['search-box'].querySelector('input');
searchBar.addEventListener('keyup',function(e){
const term = e.target.value.toLowerCase();
const words = list.getElementsByTagName('h2');
Array.from(words).forEach(function(word){
const title = word.firstElementChild.textContent;
if(title.toLowerCase().includes(term)!= -1){
word.style.display = 'block';
} else {
word.style.display = 'none';
}
})
})
为什么javascript代码在我的HTML上什么也不做?谢谢!
发布于 2018-06-25 03:38:36
const searchBar = document.querySelector('div#search-box > input');
searchBar.addEventListener('keyup',function(e){
let term = e.target.value.toLowerCase();
let words = document.querySelectorAll('div.recipe > h2');
Array.from(words).forEach(function(word){
let title = word.textContent;
if(title.toLowerCase().includes(term)){
word.parentElement.style.display = 'block';
} else {
word.parentElement.style.display = 'none';
}
});
});
<!DOCTYPE html>
<html>
<head>
<link href='style.css' rel='stylesheet' type='text/css'/>
<script src="./chat.js"></script>
</head>
<body>
<div class="col">
<div id="search-box">
<input type="text" placeholder="Search" class="input">
</div>
</div>
<main>
<div class="recipe a">
<h2>CHOCOLATE MOUSSE</h2>
<p class="description">
This delicious chocolate mousse will delight dinner guests of all ages!</p>
</div>
<div class="recipe b">
<h2>SMOKED LAMB WITH RICE</h2>
<p class="description">
Want to feel like your favorite relative came over and made you dinner? This comfort meal of smoked lamb and rice will quickly become a weekend favorite!</p>
</div>
<div class="recipe c">
<h2>GOAT CHEESE SALAD</h2>
<p class="description">
In addition to the full flavor of goat cheese, this salad includes kale, avocado, and farro to balance it out.</p>
</div>
</main>
</body>
</html>
在您的vanilla JS中发现了一些问题:
div
(H2)是由
https://stackoverflow.com/questions/51007949
复制相似问题