我有一个带有几个div的页面,每个div包含一个带有特定文本的h1,我要做的是添加一个输入字段,根据用户将在该输入字段上键入的文本,除了匹配搜索查询的行之外,所有行都将被删除(搜索应该能够选择父div,即使查询不是100%匹配h1字符串)。
这是代码的一个示例,因此如果有人键入“二钠”或“谷氨酸”,则应选择“行-1”。
<div class="col">
<div class="row-1">
<h1>Disodium/Sodium Cocoyl Glutamate</h1>
</div>
<div class="row-2">
<h1>Cetearyl Glucoside – Zuckeremulgator</h1>
</div>
<div class="row-3">
<h1>Chamomilla Recutita (Matricaria) Flower Extract – Kamille Extrakt</h1>
</div>
<div class="row-4">
<h1>Citral – Bestandteil von Zitronengrasöl</h1>
</div>
</div>
您可以通过每个子项进行映射,并找出它是否包含搜索查询,然后做您想做的任何事情,就像我改变了背景颜色一样
null
const q = "Glutamate";
const col = document.querySelector('.col');
// Array.from(col.children) this method will produce an iterable array you can map through each child
Array.from(col.children).map(child =>{
//hiding all others
if(child.querySelector('h1').innerText.indexOf(q) === -1){
child.style.display = "none";
}else{
// do what ever you want
child.style.display = "block";
// iam changing the background color to yellow
child.style.backgroundColor = "#ffff00";
}
})
<div class="col">
<div class="row-1">
<h1>Disodium/Sodium Cocoyl Glutamate</h1>
</div>
<div class="row-2">
<h1>Cetearyl Glucoside – Zuckeremulgator</h1>
</div>
<div class="row-3">
<h1>Chamomilla Recutita (Matricaria) Flower Extract – Kamille Extrakt</h1>
</div>
<div class="row-4">
<h1>Citral – Bestandteil von Zitronengrasöl</h1>
</div>
</div>