我创建了一个自定义JS搜索过滤器。逐字母搜索标记名“ h2”。
例如:<h2>CHOCOLATE MOUSSE</h2>
,<h2>SMOKED LAMB WITH RICE</h2>
在搜索栏上输入“ mo”时,两个“ display = block”。键入“ mou”时,第一个显示“ block”,第二个显示“ 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无效? 谢谢!!!!!
答案 0 :(得分:0)
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>
在您的普通JS中发现了几个问题: