实现增强型自动完成搜索与验证:教程

DDD
发布: 2025-10-16 13:47:05
原创
608人浏览过

 实现增强型自动完成搜索与验证:教程

<p>本文将指导你如何增强现有的自动完成功能,使其在文本框获得焦点时显示所有可用选项,支持在字符串中任意位置匹配搜索,并限制用户输入,确保输入值必须是自动完成列表中的有效选项。通过本文的学习,你将能够构建更加智能和用户友好的自动完成组件。</p> ### 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 < arr.length; i++) { b = document.createElement("DIV"); b.innerHTML = arr[i]; b.innerHTML += "<input type='hidden' value='" + arr[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 < 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) + "<strong>" + arr[i].substring(index, index + val.length) + "</strong>" + arr[i].substring(index + val.length); b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>"; 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) + "<strong>" + arr[i].substring(index, index + val.length) + "</strong>" + arr[i].substring(index + val.length);
登录后复制

这段代码计算出匹配字符串的起始索引,然后使用 substring 方法将匹配部分包裹在 <strong> 标签中,使其高亮显示。

3. 限制输入并进行验证

我们需要添加验证逻辑,确保用户输入的值必须是自动完成列表中的有效选项。

首先,添加一个全局变量来保存自动完成列表:

百度智能云·曦灵
百度智能云·曦灵

百度旗下的AI数字人平台

百度智能云·曦灵 83
查看详情 百度智能云·曦灵
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 += "<input type='hidden' value='" + arr[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 < 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) + "<strong>" + arr[i].substring(index, index + val.length) + "</strong>" + arr[i].substring(index + val.length);
        b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
        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();
  }
});
登录后复制

注意事项

  • 性能优化: 对于大型数据集,建议使用更高效的搜索算法,例如使用索引或前缀树。
  • 用户体验: 可以添加加载指示器,提高用户体验。
  • 安全性: 在服务器端进行验证,确保数据的安全性。
  • 样式定制: 可以根据实际需求定制自动完成列表的样式。

总结

通过修改事件监听器、匹配逻辑和添加验证,我们成功地增强了自动完成功能,使其更加智能和用户友好。 这些技术可以应用于各种场景,例如搜索框、表单输入等, 提升用户体验和数据质量。 记住,持续测试和优化是构建高质量自动完成组件的关键。

登录后复制

以上就是实现增强型自动完成搜索与验证:教程的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号