
本文将指导你如何增强现有的自动完成功能,使其在文本框获得焦点时显示所有可用选项,支持在字符串中任意位置匹配搜索,并限制用户输入,确保输入值必须是自动完成列表中的有效选项。通过本文的学习,你将能够构建更加智能和用户友好的自动完成组件。
### 1. 焦点时显示所有选项 原始代码只有在用户开始输入时才会显示自动完成选项。我们需要修改 `input` 事件监听器,使其在输入框获得焦点且没有输入任何内容时,显示整个选项列表。 修改 `inp.addEventListener("input", function(e) { ... });` 为: ```javascript inp.addEventListener("focus", function(e) { var val = this.value; // 检查是否已经有值,如果有,则不显示全部列表 if (val) return; showAllOptions(this, arr); }); function showAllOptions(inp, arr) { var a, b, i; closeAllLists(); a = document.createElement("DIV"); a.setAttribute("id", inp.id + "autocomplete-list"); a.setAttribute("class", "autocomplete-items"); inp.parentNode.appendChild(a); for (i = 0; i "; b.addEventListener("click", function(e) { inp.value = this.getElementsByTagName("input")[0].value; closeAllLists(); }); a.appendChild(b); } } inp.addEventListener("input", function(e) { var a, b, i, val = this.value; closeAllLists(); if (!val) { showAllOptions(this, arr); // 如果没有输入,显示全部列表 return false; } currentFocus = -1; a = document.createElement("DIV"); a.setAttribute("id", this.id + "autocomplete-list"); a.setAttribute("class", "autocomplete-items"); this.parentNode.appendChild(a); for (i = 0; i -1) { b = document.createElement("DIV"); // 高亮匹配部分 let index = arr[i].toUpperCase().indexOf(val.toUpperCase()); b.innerHTML = arr[i].substring(0, index) + "" + arr[i].substring(index, index + val.length) + "" + arr[i].substring(index + val.length); b.innerHTML += ""; b.addEventListener("click", function(e) { inp.value = this.getElementsByTagName("input")[0].value; closeAllLists(); }); a.appendChild(b); } } });这段代码首先添加了一个 focus 事件监听器,当输入框获得焦点时,调用 showAllOptions 函数显示所有选项。showAllOptions 函数创建并填充包含所有选项的下拉列表。同时,在 input 事件监听器中,如果输入框为空,则调用 showAllOptions 函数,确保在清除输入后也能显示所有选项。
2. 字符串任意位置匹配
原始代码只匹配字符串的开头。我们需要修改匹配逻辑,使其在字符串的任意位置进行匹配。
修改 if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) { ... } 为:
if (arr[i].toUpperCase().indexOf(val.toUpperCase()) > -1) {
// ...
}这段代码使用 indexOf 方法来检查 arr[i] 中是否包含 val。如果包含,则返回索引值(大于等于 0),否则返回 -1。
此外,为了提升用户体验,我们可以高亮显示匹配的部分:
let index = arr[i].toUpperCase().indexOf(val.toUpperCase()); b.innerHTML = arr[i].substring(0, index) + "" + arr[i].substring(index, index + val.length) + "" + arr[i].substring(index + val.length);
这段代码计算出匹配字符串的起始索引,然后使用 substring 方法将匹配部分包裹在 标签中,使其高亮显示。
3. 限制输入并进行验证
我们需要添加验证逻辑,确保用户输入的值必须是自动完成列表中的有效选项。
首先,添加一个全局变量来保存自动完成列表:
鸿思特商城系统HstShop是一款B2C独立网店系统,由拥有十年互联网开发经验的牛头带队开发完成,完全免费开源,适合大中型网站平台快速构建立强大的网上商城平台网店系统。HstShop悉心听取每一位商家的需求与建议,根据中国人的购物习惯改进了购物流程,实现更好的用户购物体验。HstShop网店系统无论在产品功能、稳定性、执行效率、负载能力、安全性和搜索引擎优化等方面都居国内同类产品领先地位,成为国内
var autocompleteList = arr;
然后在 autocomplete 函数中,将 arr 赋值给 autocompleteList。
接下来,在表单提交前,验证输入值是否在 autocompleteList 中。可以添加一个事件监听器到 form 上:
document.getElementById("regForm").addEventListener("submit", function(e) {
var inputValue = document.getElementById("myFruitList").value;
if (autocompleteList.indexOf(inputValue) === -1) {
alert("Please select a valid fruit from the autocomplete list.");
e.preventDefault(); // 阻止表单提交
}
});这段代码在表单提交时,获取输入框的值,并检查该值是否在 autocompleteList 中。如果不在,则显示警告信息并阻止表单提交。
此外,为了防止用户在选择自动完成选项后修改输入框的值,可以添加一个 blur 事件监听器:
inp.addEventListener("blur", function(e) {
var inputValue = this.value;
if (autocompleteList.indexOf(inputValue) === -1 && inputValue !== "") {
this.value = ""; // 清空输入框
}
});这段代码在输入框失去焦点时,检查输入值是否在 autocompleteList 中。如果不在且输入框不为空,则清空输入框,强制用户选择自动完成选项。
完整代码示例
function fruitautocomplete(inp, arr) {
var currentFocus;
var autocompleteList = arr; // 保存自动完成列表
inp.addEventListener("focus", function(e) {
var val = this.value;
if (val) return;
showAllOptions(this, arr);
});
function showAllOptions(inp, arr) {
var a, b, i;
closeAllLists();
a = document.createElement("DIV");
a.setAttribute("id", inp.id + "autocomplete-list");
a.setAttribute("class", "autocomplete-items");
inp.parentNode.appendChild(a);
for (i = 0; i < arr.length; i++) {
b = document.createElement("DIV");
b.innerHTML = arr[i];
b.innerHTML += "";
b.addEventListener("click", function(e) {
inp.value = this.getElementsByTagName("input")[0].value;
closeAllLists();
});
a.appendChild(b);
}
}
inp.addEventListener("input", function(e) {
var a, b, i, val = this.value;
closeAllLists();
if (!val) {
showAllOptions(this, arr);
return false;
}
currentFocus = -1;
a = document.createElement("DIV");
a.setAttribute("id", this.id + "autocomplete-list");
a.setAttribute("class", "autocomplete-items");
this.parentNode.appendChild(a);
for (i = 0; i < arr.length; i++) {
if (arr[i].toUpperCase().indexOf(val.toUpperCase()) > -1) {
b = document.createElement("DIV");
let index = arr[i].toUpperCase().indexOf(val.toUpperCase());
b.innerHTML = arr[i].substring(0, index) + "" + arr[i].substring(index, index + val.length) + "" + arr[i].substring(index + val.length);
b.innerHTML += "";
b.addEventListener("click", function(e) {
inp.value = this.getElementsByTagName("input")[0].value;
closeAllLists();
});
a.appendChild(b);
}
}
});
inp.addEventListener("keydown", function(e) {
var x = document.getElementById(this.id + "autocomplete-list");
if (x) x = x.getElementsByTagName("div");
if (e.keyCode == 40) {
currentFocus++;
addActive(x);
} else if (e.keyCode == 38) {
currentFocus--;
addActive(x);
} else if (e.keyCode == 13) {
e.preventDefault();
if (currentFocus > -1) {
if (x) x[currentFocus].click();
}
}
});
inp.addEventListener("blur", function(e) {
var inputValue = this.value;
if (autocompleteList.indexOf(inputValue) === -1 && inputValue !== "") {
this.value = ""; // 清空输入框
}
});
function addActive(x) {
if (!x) return false;
removeActive(x);
if (currentFocus >= x.length) currentFocus = 0;
if (currentFocus < 0) currentFocus = (x.length - 1);
x[currentFocus].classList.add("autocomplete-active");
}
function removeActive(x) {
for (var i = 0; i < x.length; i++) {
x[i].classList.remove("autocomplete-active");
}
}
function closeAllLists(elmnt) {
var x = document.getElementsByClassName("autocomplete-items");
for (var i = 0; i < x.length; i++) {
if (elmnt != x[i] && elmnt != inp) {
x[i].parentNode.removeChild(x[i]);
}
}
}
document.addEventListener("click", function(e) {
closeAllLists(e.target);
});
}
var fruitlist = [
"Apple",
"Mango",
"Pear",
"Banana",
"Berry"
];
fruitautocomplete(document.getElementById("myFruitList"), fruitlist);
document.getElementById("regForm").addEventListener("submit", function(e) {
var inputValue = document.getElementById("myFruitList").value;
if (fruitlist.indexOf(inputValue) === -1) {
alert("Please select a valid fruit from the autocomplete list.");
e.preventDefault();
}
});注意事项
- 性能优化: 对于大型数据集,建议使用更高效的搜索算法,例如使用索引或前缀树。
- 用户体验: 可以添加加载指示器,提高用户体验。
- 安全性: 在服务器端进行验证,确保数据的安全性。
- 样式定制: 可以根据实际需求定制自动完成列表的样式。
总结
通过修改事件监听器、匹配逻辑和添加验证,我们成功地增强了自动完成功能,使其更加智能和用户友好。 这些技术可以应用于各种场景,例如搜索框、表单输入等, 提升用户体验和数据质量。 记住,持续测试和优化是构建高质量自动完成组件的关键。









