我有以下代码来显示带有用于自动完成的单词的列表:
var words = ['foo', 'bar', 'barz', 'ba'];
var possibleWords = [];
document.getElementsByTagName('div')[0].addEventListener('keyup', function(){
var textWords = this.innerText.split(' ');
var lastWord = textWords[textWords.length-1];
for(var k = 0; k < words.length; k++){
for(n = 0; n < 20; n++){
if(lastWord.length == n+1 && words[k].charAt(n) == lastWord.charAt(n)){
possibleWords.push(words[k]);
var counts = possibleWords.reduce((a, c) => {
a[c] = (a[c] || 0) + 1;
return a;
}, {});
var maxCount = Math.max(...Object.values(counts));
var mostFrequent = Object.keys(counts).filter(k => counts[k] === maxCount);
}
}
}
console.log(mostFrequent);
var list = this.getElementsByTagName('ul')[0];
if(mostFrequent == undefined) {
list.removeAttribute('style');
} else {
list.style.display = 'inline';
list.innerHTML = '';
list.innerHTML = '<li>'+mostFrequent.join('</li><li>')+'</li>';
}
});
div{
width:300px;
height:100px;
outline:1px solid #ccc;
position:relative;
}
ul{
display:none;
position:absolute;
left:0;
top:100px;
}
<div contenteditable="true"><ul></ul></div>
当我从var list = ...to注释底部代码list.innerHTML = '<li>'+...并尝试键入b,然后是ba,然后是bar,然后是barz 时,我在控制台中看到了正确的结果。但是如果我不注释底部代码,我会收到undefined一半的时间并且列表也有一半的时间是隐藏的。
如何解决问题?
跃然一笑
相关分类