每当我尝试将输入放入搜索栏中时,它都会返回数据。过滤器不是函数错误。坚持了几天,我可能只是不知道一些基本规则,哈哈
这是我用于搜索栏功能的 JS、JSON 和 HTML
const searchBar = document.getElementById('myInput')
let data = [];
console.log(searchBar)
searchBar.addEventListener('keyup', e => {
const searchTarg = e.target.value.toLowerCase();
const searchFilter = data.filter(info => {
return (
info.fields.toLowerCase().includes(searchTarg) ||
info.title.toLowerCase().includes(searchTarg)
)
})
displayProducts(searchFilter)
});
{
"items": [
{
"sys": { "id": "1" },
"fields": {
"title": "queen panel bed",
"price": 10.99,
"image": { "fields": { "file": { "url": "./images/product-1.jpeg" } } }
}
},
{
"sys": { "id": "2" },
"fields": {
"title": "king panel bed",
"price": 12.99,
"image": { "fields": { "file": { "url": "./images/product-2.jpeg" } } }
}
},
{
"sys": { "id": "3" },
"fields": {
"title": "single panel bed",
"price": 12.99,
"image": { "fields": { "file": { "url": "./images/product-3.jpeg" } } }
}
}
}
<input type="text" id="myInput" onkeyup="navSearch()" placeholder="Search for names..">
<ul id="myUL">
<li><a href="#">Adele</a></li>
<li><a href="#">Agnes</a></li>
<li><a href="#">Billy</a></li>
<li><a href="#">Bob</a></li>
<li><a href="#">Calvin</a></li>
<li><a href="#">Christina</a></li>
<li><a href="#">Cindy</a></li>
</ul>
我是根据很多教程做的,可以链接我为搜索栏观看的那个,但如果这违反任何规则,请在此处链接,感谢阅读^^
答案 0 :(得分:0)
您不需要为 onkeyup 函数添加任何事件监听器,您可以通过 navSearch 函数进行搜索
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<input
type="text"
id="myInput"
onkeyup="navSearch()"
placeholder="Search for names.."
/>
<ul id="myUL">
<li><a href="#">Adele</a></li>
<li><a href="#">Agnes</a></li>
<li><a href="#">Billy</a></li>
<li><a href="#">Bob</a></li>
<li><a href="#">Calvin</a></li>
<li><a href="#">Christina</a></li>
<li><a href="#">Cindy</a></li>
</ul>
<script>
let data = [
{
sys: { id: "1" },
fields: {
title: "queen panel bed",
price: 10.99,
image: { fields: { file: { url: "./images/product-1.jpeg" } } },
},
},
{
sys: { id: "2" },
fields: {
title: "king panel bed",
price: 12.99,
image: { fields: { file: { url: "./images/product-2.jpeg" } } },
},
},
{
sys: { id: "3" },
fields: {
title: "single panel bed",
price: 12.99,
image: { fields: { file: { url: "./images/product-3.jpeg" } } },
},
},
];
function navSearch() {
const searchBar = document.getElementById("myInput");
const searchTarg = searchBar.value;
const searchFilter = data.filter((info) => {
return info.fields.title.toLowerCase().includes(searchTarg);
});
console.log(searchFilter);
}
</script>
</body>
</html>