我进行了自动填充搜索,当您在表单字段中键入内容时,它将填充来自数组的结果的下拉列表。
我遇到的问题是,当您在下拉列表之外单击时,它会按原样消失,但是当您再次开始在表单字段中键入内容时,该下拉列表将不会显示。我正在尝试使用jQuery实现此目标:
这是在搜索字段下显示下拉列表:
const input = document.querySelector('#FAVORITE_LOCATION');
const suggestions = document.querySelector('.suggestions ul');
const country = ['USA', 'Canada'];
function search(str) {
let results = [];
const val = str.toLowerCase();
for (i = 0; i < country.length; i++) {
if (country[i].toLowerCase().indexOf(val) > -1) {
results.push(country[i]);
}
}
return results;
}
function searchHandler(e) {
const inputVal = e.currentTarget.value;
let results = [];
if (inputVal.length > 0) {
results = search(inputVal);
}
showSuggestions(results);
}
function showSuggestions(results) {
suggestions.innerHTML = '';
if (results.length > 0) {
for (i = 0; i < results.length; i++) {
suggestions.innerHTML += `<li>${results[i]}</li>`;
}
suggestions.classList.add('has-suggestions');
} else {
results = [];
suggestions.innerHTML = '';
suggestions.classList.remove('has-suggestions');
}
}
function useSuggestion(e) {
input.value = e.target.innerText;
input.focus();
suggestions.innerHTML = '';
suggestions.classList.remove('has-suggestions');
}
input.addEventListener('keyup', searchHandler);
suggestions.addEventListener('click', useSuggestion);
下面是我要隐藏填充的自动填充的地方:
$(document).on('click', function(event){
var container = $("ul.has-suggestions");
if (!container.is(event.target) &&
container.has(event.target).length === 0)
{
container.hide();
}else{
container.show();
}
});
最后,这是下拉菜单本身的CSS
.search-container {
position: relative;
}
.search-container input,
.search-container .suggestions {
width: 100%;
}
.search-container input {
background-color: white;
height: 60px;
padding: 0 10px;
}
.search-container .suggestions {
position: absolute;
top: 80px;
}
ul {
display: none;
list-style-type: none;
padding: 0;
margin: 0;
box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.2);
max-height: 200px;
overflow-y: auto;
}
ul.has-suggestions {
display: block;
}
ul li {
padding: 10px;
cursor: pointer;
background-color: white;
color: black;
}
当用户开始在表单字段中键入时,ul.has-uggestions设置为display:block,然后显示填充的下拉列表。我试图使用if / else语句并使用.show();但它似乎不起作用。
任何帮助将不胜感激!
谢谢!
答案 0 :(得分:2)
您可能想要执行以下操作来显示和/或隐藏自动完成建议:
input.addEventListener('blur', function() {
$("ul.has-suggestions").hide();
})
input.addEventListener('focus', function() {
$("ul.has-suggestions").show();
})
编辑2并请求更新; codepen with example
第二个Codepen用单击的值填充表单字段。