“我在代码中遇到了搜索功能的问题。当我输入搜索输入时,结果似乎没有正确更新。您能否帮助我了解可能导致此问题的原因
let productContainer = document.querySelector('.product-container')
let arr_1 = [];
let arr_2 = [];
let search = document.querySelector('#search')
function getDataJson() {
fetch(`http://localhost:3000/services`)
.then(response => response.json())
.then(data => {
arr_2 = data;
productContainer.innerHTML = "";
arr_1 = arr_1.length || search.value ? arr_1 : data;
arr_1.forEach(element => {
productContainer.innerHTML += `
<div class="product-image"><img src="${element.images}" alt=""></div>
<h2>${element.title}</h2>
`
});
})
}
getDataJson()
search.addEventListener("input", (e) => {
arr_1 = arr_2;
arr_1 = arr_1.filter((el) => {
return el.title.toLowerCase().includes(e.target.value.toLowerCase())
});
getDataJson();
})
我的 JavaScript 代码中的搜索功能遇到问题。当我输入搜索词时,它似乎没有按预期工作。您能否指导我如何排查和解决此问题
由于您没有进行服务器端过滤,因此从事件列表中删除
getDataJson();
let productContainer = document.querySelector('.product-container');
let arr_1 = [];
let arr_2 = [];
let search = document.querySelector('#search');
function getDataJson() {
fetch(`http://localhost:3000/services`)
.then(response => response.json())
.then(data => {
arr_2 = data;
productContainer.innerHTML = "";
arr_1 = arr_1.length || search.value ? arr_1 : data;
arr_1.forEach(element => {
productContainer.innerHTML += `
<div class="product-image"><img src="${element.images}" alt=""></div>
<h2>${element.title}</h2>
`;
});
});
}
getDataJson();
search.addEventListener("input", (e) => {
arr_1 = arr_2.filter((el) => {
return el.title.toLowerCase().includes(e.target.value.toLowerCase());
});
productContainer.innerHTML = ""; // Clear the container before rendering new results
arr_1.forEach(element => {
productContainer.innerHTML += `
<div class="product-image"><img src="${element.images}" alt=""></div>
<h2>${element.title}</h2>
`;
});
});