0

0

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

DDD

DDD

发布时间:2025-10-16 13:47:05

|

611人浏览过

|

来源于php中文网

原创

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

<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. 限制输入并进行验证

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

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

AITDK
AITDK

免费AI SEO工具,SEO的AI生成器

下载
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();
  }
});

注意事项

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

总结

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

					

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

WorkBuddy
WorkBuddy

腾讯云推出的AI原生桌面智能体工作台

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
if什么意思
if什么意思

if的意思是“如果”的条件。它是一个用于引导条件语句的关键词,用于根据特定条件的真假情况来执行不同的代码块。本专题提供if什么意思的相关文章,供大家免费阅读。

847

2023.08.22

全局变量怎么定义
全局变量怎么定义

本专题整合了全局变量相关内容,阅读专题下面的文章了解更多详细内容。

95

2025.09.18

python 全局变量
python 全局变量

本专题整合了python中全局变量定义相关教程,阅读专题下面的文章了解更多详细内容。

106

2025.09.18

js 字符串转数组
js 字符串转数组

js字符串转数组的方法:1、使用“split()”方法;2、使用“Array.from()”方法;3、使用for循环遍历;4、使用“Array.split()”方法。本专题为大家提供js字符串转数组的相关的文章、下载、课程内容,供大家免费下载体验。

760

2023.08.03

js截取字符串的方法
js截取字符串的方法

js截取字符串的方法有substring()方法、substr()方法、slice()方法、split()方法和slice()方法。本专题为大家提供字符串相关的文章、下载、课程内容,供大家免费下载体验。

221

2023.09.04

java基础知识汇总
java基础知识汇总

java基础知识有Java的历史和特点、Java的开发环境、Java的基本数据类型、变量和常量、运算符和表达式、控制语句、数组和字符串等等知识点。想要知道更多关于java基础知识的朋友,请阅读本专题下面的的有关文章,欢迎大家来php中文网学习。

1567

2023.10.24

字符串介绍
字符串介绍

字符串是一种数据类型,它可以是任何文本,包括字母、数字、符号等。字符串可以由不同的字符组成,例如空格、标点符号、数字等。在编程中,字符串通常用引号括起来,如单引号、双引号或反引号。想了解更多字符串的相关内容,可以阅读本专题下面的文章。

651

2023.11.24

java读取文件转成字符串的方法
java读取文件转成字符串的方法

Java8引入了新的文件I/O API,使用java.nio.file.Files类读取文件内容更加方便。对于较旧版本的Java,可以使用java.io.FileReader和java.io.BufferedReader来读取文件。在这些方法中,你需要将文件路径替换为你的实际文件路径,并且可能需要处理可能的IOException异常。想了解更多java的相关内容,可以阅读本专题下面的文章。

1228

2024.03.22

TypeScript类型系统进阶与大型前端项目实践
TypeScript类型系统进阶与大型前端项目实践

本专题围绕 TypeScript 在大型前端项目中的应用展开,深入讲解类型系统设计与工程化开发方法。内容包括泛型与高级类型、类型推断机制、声明文件编写、模块化结构设计以及代码规范管理。通过真实项目案例分析,帮助开发者构建类型安全、结构清晰、易维护的前端工程体系,提高团队协作效率与代码质量。

26

2026.03.13

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
React 教程
React 教程

共58课时 | 6万人学习

TypeScript 教程
TypeScript 教程

共19课时 | 3.4万人学习

Bootstrap 5教程
Bootstrap 5教程

共46课时 | 3.6万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

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