我正在尝试创建一个实时匹配数据显示器。 (即,我有一个数据数组,当用户在文本框中输入一个字符串时,将显示该数组中匹配的字符串)。
但是在这里出现一个小问题,当我尝试显示新的匹配数据时,旧数据也会附加结果。
例如 假设数组为=> ['abcd','aaa','bcd','aabb']
I)。首先,我输入字母“ a”
然后输出为
- abcd
- aaa
- aabb
II)。然后我再添加一个字母“ aa”
预期输出:
- aaa
- aabb
返回的输出按程序:
- abcd
- aaa
- aabb
- aaa
- aabb
代码在这里
var elemContainer = ['abcd','aaa','bcd','aabb'];
var matchedItems = [];
var result = '';
function showSearchData(){
document.getElementById('search').addEventListener('keyup',function(){
/*console.log(this.value);*/
var data = this.value;
for(let i=0;i < elemContainer.length; i++){
if(elemContainer[i].includes(data)){
matchedItems.push(elemContainer[i]);
}
}
result = '';
console.log(result);
displayMatchedData();
});
}
function displayMatchedData(){
/*result = '';*/
document.getElementById('matched-items-container').innerHTML = '';
for(let i=0;i<= matchedItems.length;i++){
result += '<li>'+matchedItems[i]+'</li>';
}
document.getElementById('matched-items-container').innerHTML = result;
}
showSearchData();
<input type="text" id="search" />
<ul id="matched-items-container"></ul>
到目前为止我尝试过的
I.每当发生keyup
事件时,都要重置结果变量。
二。每次调用display()时,请将element.innerHTML
设置为NULL。
答案 0 :(得分:1)
您忘记清除matchedItems
数组。
var elemContainer = ['abcd','aaa','bcd','aabb'];
var matchedItems = [];
var result = '';
function showSearchData(){
document.getElementById('search').addEventListener('keyup',function(){
/*console.log(this.value);*/
var data = this.value;
// here, clear the matched items array
matchedItems = [];
for(let i=0;i < elemContainer.length; i++){
if(elemContainer[i].includes(data)){
matchedItems.push(elemContainer[i]);
}
}
result = '';
console.log(result);
displayMatchedData();
});
}
function displayMatchedData(){
/*result = '';*/
document.getElementById('matched-items-container').innerHTML = '';
for(let i=0;i<= matchedItems.length;i++){
result += '<li>'+matchedItems[i]+'</li>';
}
document.getElementById('matched-items-container').innerHTML = result;
}
showSearchData();
<input type="text" id="search" />
<ul id="matched-items-container"></ul>
答案 1 :(得分:1)
每执行一次matchedItems
操作就清除您的keyup
数组,而且您的计数器也从0开始,因此此行for(let i=0; i<= matchedItems.length; i++)
必须不包含=
,否则它会给您{{ 1}}
undefined
var elemContainer = ['abcd','aaa','bcd','aabb'];
var matchedItems = [];
var result = '';
function showSearchData(){
document.getElementById('search').addEventListener('keyup',function(){
matchedItems = [];
var data = this.value;
for(let i=0;i < elemContainer.length; i++){
if(elemContainer[i].includes(data)){
matchedItems.push(elemContainer[i]);
}
}
result = '';
console.log(result);
displayMatchedData();
});
}
function displayMatchedData(){
/*result = '';*/
document.getElementById('matched-items-container').innerHTML = '';
for(let i=0;i< matchedItems.length;i++){
result += '<li>'+matchedItems[i]+'</li>';
}
document.getElementById('matched-items-container').innerHTML = result;
}
showSearchData();