【发布时间】:2019-05-25 00:46:24
【问题描述】:
这几天我一直在为同一段代码苦苦挣扎......
所以对于 html 部分,我有这个:
<input type="text" id="search_immobilier_ville" name="search_immobilier[ville]">
<div class="collection" id="search-ville-collection"></div>
我有一个输入,我必须输入任何城市名称,然后我想将匹配的城市名称过滤到现有的城市数组中,如下所示:
let api_results = [['Le Moule',97152],['Lamentin',97189],...]
let ville_input = document.getElementById('search_immobilier_ville');
然后将匹配的城市显示为 div #search-ville-collection 中的元素列表。
在每个 keyup 事件上,我都需要执行这个动作,并实时更新视觉列表。
我的问题是我的过滤系统搞砸了,例如,如果我搜索“lam”,我可以得到一个名为“lamentin”的城市(通过测试),另一个只有"la" 匹配像 "capesterre-de-marie-galante"
到目前为止,我已经做到了:
// Previously filled by an API
let api_results = [[name,postalCode],[name,postalCode],...];
ville_input.addEventListener('keyup', () => {
let value = ville_input.value.toUpperCase().trim();
// User input
let input_val = ville_input.value.toUpperCase().trim();
// Filtering through var ville_input
api_results.forEach(el => {
if (el[0].toUpperCase().startsWith(input_val) || input_val.length >= 2 && el[0].toUpperCase().includes(input_val)) {
result_list.style.display = 'block';
// if city not present in the html list, add it
if (document.getElementById(el[1]) === null) {
$(result_list).append(`<a class="collection-item search-ville-results" id="${el[1]}"> ${el[0]} - ${el[1]} </a>`);
}
}
}); // End forEach
/* Looping through the collection child nodes to check
if there are cities that don't match the user input */
for (let child of result_list.children) {
console.log(child)
// if the user input doesn't match with an existing city in the node, delete the node
if (!child.text.toUpperCase().includes(input_val)) {
result_list.removeChild(child);
}
}
// Highlight first element of the list
result_list.firstElementChild.classList.add('active');
// empty results div if user input is empty
if (input_val == '') {
result_list.style.display = 'none';
result_list.innerHTML = '';
}
});
此代码部分有效。例如,如果我输入“lam”,我应该根据我的结果集只得到一个结果,但是看看这个场景:
输入“l”:
输入“la”:
输入“lam”:
(在这里你开始看到问题)
输入“蹩脚”:
我确定我的代码有问题,但我不知道是什么问题。
【问题讨论】:
-
复制Removing LI from UL in for loop (JS),即使你没有使用
li,原理是一样的。
标签: javascript html arrays filter