根据输入值/javascript 过滤数组对象
2020-03-28
1322
我试图根据用户输入从数组列表中过滤对象,但我不确定如何实现这一点。
这是我的 html:
<input id="search" type="text" placeholder="Search..">
<div id="animallist"></div>
javascript:
const animals = [{
name: "Cat",
useful: "no"
},
{
name: "Dog",
useful: "yes"
},
{
name: "Fish",
useful: "no"
}
]
animals.forEach(addLink);
function addLink(animal, i) {
const div = document.createElement('div');
const animalList = document.createElement('h2');
animalList.innerHTML = animal.name + " " +"-"+"useful?" + " "+ animal.useful;
animalList.style.cssText = "text-align:center;"
div.appendChild(animalList);
animallist.appendChild(div);
}
我不知道这是否可行,但我想这样做,这样它就会实时过滤项目,所以如果我在搜索框中输入字母
C
,那么它将消除数组列表中的另外 2 个项目并仅显示
Cat
。
2个回答
您可以编辑
addLink
以包含
div.dataset.animalName = animal.name;
,并添加以下代码:
search.addEventListener("keyup", function() {
Array.from(animallist.children).forEach(d => {
if (d.dataset.animalName.toLowerCase().indexOf(this.value.toLowerCase()) != -1) {
d.style.display = "block";
} else {
d.style.display = "none";
}
});
});
请参阅 这个 fiddle 。
Aplet123
2020-03-28
您还可以执行如下操作:
const animals = [{
name: "Cat",
useful: "no"
},
{
name: "Dog",
useful: "yes"
},
{
name: "Fish",
useful: "no"
}
];
const select = document.querySelector("#search");
const AnimalList = document.querySelector("#animallist");
select.onkeyup = function search() {
const {
value
} = select;
if (value) {
animals.filter(({
name
}) => {
if (name.toUpperCase().indexOf(value.toUpperCase()) > -1) {
AnimalList.innerHTML = name
}
})
} else {
AnimalList.innerHTML = "try again...";
}
}
#animallist {
margin-top: 10px;
padding: 10px;
background: #8e44ad;
color: #fff;
}
<input id="search" type="text" placeholder="Search..">
<div id="animallist">search for an animal...</div>
Aziz.G
2020-03-28