0

0

将HTML输入与JavaScript函数连接以实现数据过滤

霞舞

霞舞

发布时间:2025-11-11 11:33:02

|

479人浏览过

|

来源于php中文网

原创

将html输入与javascript函数连接以实现数据过滤

本教程详细介绍了如何通过JavaScript获取HTML输入框中的用户数据,并将其传递给JavaScript函数以实现数据过滤功能。我们将通过一个具体的职位搜索案例,演示如何使用document.getElementById().value获取输入值,处理大小写不敏感的搜索,并动态地根据用户输入筛选数据。

在现代Web应用开发中,与用户交互并根据其输入动态处理数据是一项基本且重要的能力。本教程将引导您完成一个常见场景:从HTML表单的输入框中获取用户输入的文本,并将其作为参数传递给JavaScript函数,进而对预定义的数据集进行筛选。我们将以一个职位搜索应用为例,展示如何实现这一功能。

1. HTML结构:定义输入与触发按钮

首先,我们需要在HTML页面上创建用户输入界面。这包括两个文本输入框,分别用于输入职位名称和地点,以及一个按钮来触发搜索操作。




    
    
    职位搜索器


    

关键点:

立即学习Java免费学习笔记(深入)”;

  • id="titleInput" 和 id="locationInput":为输入框设置唯一的ID,这是JavaScript获取其值的关键。
  • type="button":确保按钮不会提交表单,而是只触发JavaScript函数。
  • onclick="searchJobs()":当按钮被点击时,将调用名为 searchJobs 的JavaScript函数。

2. JavaScript数据与过滤逻辑

接下来,我们定义一个职位数据集,并编写一个JavaScript函数来执行过滤逻辑。

// script.js

const jobs = [{
    title: "Marketing Intern",
    location: "US, NY, New York"
  },
  {
    title: "Customer Service - Cloud Video Production",
    location: "NZ, Auckland",
  },
  {
    title: "Commissioning Machinery Assistant (CMA)",
    location: "US, IA, Wever",
  },
  {
    title: "Account Executive - Washington DC",
    location: "US, DC, Washington",
  },
  {
    title: "Bill Review Manager",
    location: "US, FL, Fort Worth"
  },
  {
    title: "Accounting Clerk",
    location: "US, MD,"
  },
  {
    title: "Head of Content (m/f)",
    location: "DE, BE, Berlin"
  },
  {
    title: "Lead Guest Service Specialist",
    location: "US, CA, San Francisco",
  },
  {
    title: "HP BSM SME",
    location: "US, FL, Pensacola"
  },
  {
    title: "Customer Service Associate - Part Time",
    location: "US, AZ, Phoenix",
  },
  {
    title: "ASP.net Developer Job opportunity at United States,New Jersey",
    location: "US, NJ, Jersey City",
  },
  {
    title: "Talent Sourcer (6 months fixed-term contract)",
    location: "GB, LND, London",
  },
  {
    title: "Applications Developer, Digital",
    location: "US, CT, Stamford",
  },
  {
    title: "Installers",
    location: "US, FL, Orlando"
  },
  {
    title: "Account Executive - Sydney",
    location: "AU, NSW, Sydney"
  },
  {
    title: "VP of Sales - Vault Dragon",
    location: "SG, 01, Singapore",
  },
  {
    title: "Hands-On QA Leader",
    location: "IL, Tel Aviv, Israel"
  },
  {
    title: "Southend-on-Sea Traineeships Under NAS 16-18 Year Olds Only",
    location: "GB, SOS, Southend-on-Sea",
  },
  {
    title: "Visual Designer",
    location: "US, NY, New York"
  },
  {
    title: "Process Controls Engineer - DCS PLC MS Office - PA",
    location: "US, PA, USA Northeast",
  },
  {
    title: "Marketing Assistant",
    location: "US, TX, Austin"
  },
  {
    title: "Front End Developer",
    location: "NZ, N, Auckland"
  },
  {
    title: "Engagement Manager",
    location: "AE,"
  },
  {
    title: "Vice President, Sales and Sponsorship (Businessfriend.com)",
    location: "US, CA, Carlsbad",
  },
  {
    title: "Customer Service",
    location: "GB, LND, London"
  },
  {
    title: "H1B SPONSOR FOR L1/L2/OPT",
    location: "US, NY, New York"
  },
  {
    title: "Marketing Exec",
    location: "SG,"
  },
  {
    title: "HAAD/DHA Licensed Doctors Opening in UAE",
    location: "AE, AZ, Abudhabi",
  },
  {
    title: "Talent Management Process Manager",
    location: "US, MO, St. Louis",
  },
  {
    title: "Customer Service Associate",
    location: "CA, ON, Toronto"
  },
  {
    title: "Customer Service Technical Specialist",
    location: "US, MA, Waltham",
  },
  {
    title: "Software Applications Specialist",
    location: "US, KS,"
  },
  {
    title: "Craftsman Associate",
    location: "US, WA, Everett"
  },
  {
    title: "Completion Engineer",
    location: "US, CA, San Ramon"
  },
  {
    title: "I Want To Work At Karmarama",
    location: "GB, LND,"
  },
  {
    title: "English Teacher Abroad",
    location: "US, NY, Saint Bonaventure",
  },
];

/**
 * 根据标题和地点筛选职位。
 * @param {string} titleFilter 用户输入的职位标题关键词。
 * @param {string} locationFilter 用户输入的地点关键词。
 * @returns {Array} 匹配的职位列表。
 */
function findJobs(titleFilter, locationFilter) {
  const matchedJobs = [];

  // 将过滤关键词转换为小写,以便进行不区分大小写的匹配
  const lowerTitleFilter = titleFilter.toLowerCase();
  const lowerLocationFilter = locationFilter.toLowerCase();

  jobs.forEach(job => {
    const lowercaseTitle = job.title.toLowerCase();
    const lowercaseLocation = job.location.toLowerCase();

    // 使用 includes() 方法检查关键词是否存在于职位标题或地点中
    if (lowercaseTitle.includes(lowerTitleFilter) &&
        lowercaseLocation.includes(lowerLocationFilter)) {
      matchedJobs.push(job);
    }
  });

  return matchedJobs;
}

关键点:

立即学习Java免费学习笔记(深入)”;

  • jobs 数组:存储了所有职位数据,每个职位都是一个包含 title 和 location 属性的对象。
  • findJobs(titleFilter, locationFilter) 函数:
    • 接收两个参数:titleFilter 和 locationFilter,分别代表用户输入的职位标题和地点。
    • 在进行比较之前,将所有字符串(包括原始数据和过滤关键词)都转换为小写,确保搜索是不区分大小写的。
    • 使用 forEach 遍历 jobs 数组。
    • String.prototype.includes():这是一个非常有用的字符串方法,用于检查一个字符串是否包含另一个字符串。
    • 函数返回一个包含所有匹配职位的新数组。

3. 连接HTML输入与JavaScript函数

现在,最关键的一步是获取用户在HTML输入框中输入的值,并将其传递给 findJobs 函数。这需要用到 document.getElementById() 和 .value 属性。

我们将在 script.js 中添加 searchJobs() 函数,它将在按钮被点击时执行。

Type
Type

生成草稿,转换文本,获得写作帮助-等等。

下载
// script.js (接上文)

// ... (jobs 数组和 findJobs 函数定义) ...

function searchJobs() {
  // 1. 获取输入框元素
  const titleInput = document.getElementById('titleInput');
  const locationInput = document.getElementById('locationInput');

  // 2. 获取输入框的当前值
  const titleValue = titleInput.value;
  const locationValue = locationInput.value;

  // 3. 调用 findJobs 函数进行筛选
  const results = findJobs(titleValue, locationValue);

  // 4. 将结果显示在页面上 (而非仅仅 console.log)
  displayResults(results);
}

/**
 * 将搜索结果显示在HTML页面上。
 * @param {Array} results 匹配的职位列表。
 */
function displayResults(results) {
  const resultsDiv = document.getElementById('results');
  resultsDiv.innerHTML = ''; // 清空之前的搜索结果

  if (results.length === 0) {
    resultsDiv.innerHTML = '

未找到匹配的职位。

'; return; } const ul = document.createElement('ul'); results.forEach(job => { const li = document.createElement('li'); li.textContent = `${job.title} - ${job.location}`; ul.appendChild(li); }); resultsDiv.appendChild(ul); const countP = document.createElement('p'); countP.textContent = `找到 ${results.length} 个职位。`; resultsDiv.appendChild(countP); }

关键点:

立即学习Java免费学习笔记(深入)”;

  • document.getElementById('id'):这个方法通过元素的 id 属性来获取对应的HTML元素对象。
  • .value:这是HTML表单元素(如
  • searchJobs() 函数负责:
    1. 通过ID获取两个输入框元素。
    2. 读取它们的 .value 属性,获取用户输入的字符串。
    3. 将这些值作为参数传递给 findJobs 函数。
    4. 调用 displayResults 函数,将筛选出的职位列表呈现在页面上,而不是只在控制台输出。这样用户才能直观地看到结果。

完整代码示例

将上述HTML和JavaScript代码分别保存为 index.html 和 script.js,并确保它们在同一目录下。

index.html:




    
    
    职位搜索器
    


    

职位搜索

script.js:

const jobs = [
  { title: "Marketing Intern", location: "US, NY, New York" },
  { title: "Customer Service - Cloud Video Production", location: "NZ, Auckland" },
  { title: "Commissioning Machinery Assistant (CMA)", location: "US, IA, Wever" },
  { title: "Account Executive - Washington DC", location: "US, DC, Washington" },
  { title: "Bill Review Manager", location: "US, FL, Fort Worth" },
  { title: "Accounting Clerk", location: "US, MD," },
  { title: "Head of Content (m/f)", location: "DE, BE, Berlin" },
  { title: "Lead Guest Service Specialist", location: "US, CA, San Francisco" },
  { title: "HP BSM SME", location: "US, FL, Pensacola" },
  { title: "Customer Service Associate - Part Time", location: "US, AZ, Phoenix" },
  { title: "ASP.net Developer Job opportunity at United States,New Jersey", location: "US, NJ, Jersey City" },
  { title: "Talent Sourcer (6 months fixed-term contract)", location: "GB, LND, London" },
  { title: "Applications Developer, Digital", location: "US, CT, Stamford" },
  { title: "Installers", location: "US, FL, Orlando" },
  { title: "Account Executive - Sydney", location: "AU, NSW, Sydney" },
  { title: "VP of Sales - Vault Dragon", location: "SG, 01, Singapore" },
  { title: "Hands-On QA Leader", location: "IL, Tel Aviv, Israel" },
  { title: "Southend-on-Sea Traineeships Under NAS 16-18 Year Olds Only", location: "GB, SOS, Southend-on-Sea" },
  { title: "Visual Designer", location: "US, NY, New York" },
  { title: "Process Controls Engineer - DCS PLC MS Office - PA", location: "US, PA, USA Northeast" },
  { title: "Marketing Assistant", location: "US, TX, Austin" },
  { title: "Front End Developer", location: "NZ, N, Auckland" },
  { title: "Engagement Manager", location: "AE," },
  { title: "Vice President, Sales and Sponsorship (Businessfriend.com)", location: "US, CA, Carlsbad" },
  { title: "Customer Service", location: "GB, LND, London" },
  { title: "H1B SPONSOR FOR L1/L2/OPT", location: "US, NY, New York" },
  { title: "Marketing Exec", location: "SG," },
  { title: "HAAD/DHA Licensed Doctors Opening in UAE", location: "AE, AZ, Abudhabi" },
  { title: "Talent Management Process Manager", location: "US, MO, St. Louis" },
  { title: "Customer Service Associate", location: "CA, ON, Toronto" },
  { title: "Customer Service Technical Specialist", location: "US, MA, Waltham" },
  { title: "Software Applications Specialist", location: "US, KS," },
  { title: "Craftsman Associate", location: "US, WA, Everett" },
  { title: "Completion Engineer", location: "US, CA, San Ramon" },
  { title: "I Want To Work At Karmarama", location: "GB, LND," },
  { title: "English Teacher Abroad", location: "US, NY, Saint Bonaventure" },
];

/**
 * 根据标题和地点筛选职位。
 * @param {string} titleFilter 用户输入的职位标题关键词。
 * @param {string} locationFilter 用户输入的地点关键词。
 * @returns {Array} 匹配的职位列表。
 */
function findJobs(titleFilter, locationFilter) {
  const matchedJobs = [];

  // 将过滤关键词转换为小写,以便进行不区分大小写的匹配
  const lowerTitleFilter = titleFilter.toLowerCase();
  const lowerLocationFilter = locationFilter.toLowerCase();

  jobs.forEach(job => {
    const lowercaseTitle = job.title.toLowerCase();
    const lowercaseLocation = job.location.toLowerCase();

    // 使用 includes() 方法检查关键词是否存在于职位标题或地点中
    if (lowercaseTitle.includes(lowerTitleFilter) &&
        lowercaseLocation.includes(lowerLocationFilter)) {
      matchedJobs.push(job);
    }
  });

  return matchedJobs;
}

function searchJobs() {
  // 1. 获取输入框元素
  const titleInput = document.getElementById('titleInput');
  const locationInput = document.getElementById('locationInput');

  // 2. 获取输入框的当前值
  const titleValue = titleInput.value.trim(); // 使用 trim() 移除首尾空白
  const locationValue = locationInput.value.trim();

  // 3. 调用 findJobs 函数进行筛选
  const results = findJobs(titleValue, locationValue);

  // 4. 将结果显示在页面上
  displayResults(results);
}

/**
 * 将搜索结果显示在HTML页面上。
 * @param {Array} results 匹配的职位列表。
 */
function displayResults(results) {
  const resultsDiv = document.getElementById('results');
  resultsDiv.innerHTML = ''; // 清空之前的搜索结果

  if (results.length === 0) {
    resultsDiv.innerHTML = '

未找到匹配的职位。

'; return; } const ul = document.createElement('ul'); results.forEach(job => { const li = document.createElement('li'); li.textContent = `${job.title} - ${job.location}`; ul.appendChild(li); }); resultsDiv.appendChild(ul); const countP = document.createElement('p'); countP.textContent = `找到 ${results.length} 个职位。`; resultsDiv.appendChild(countP); }

注意事项与最佳实践

  1. ID的唯一性: document.getElementById() 依赖于ID的唯一性。确保您的HTML文档中每个元素的ID都是独一无二的。
  2. 大小写处理: 在进行字符串比较时,通常建议将所有字符串转换为相同的大小写(例如,都转换为小写),以实现不区分大小写的搜索,提高用户体验。本教程在 findJobs 函数内部处理了这一逻辑。
  3. 输入验证: 在实际应用中,您可能需要对用户输入进行验证,例如检查输入是否为空,或者是否符合特定的格式要求。
  4. 事件监听器: 尽管 onclick 属性简单易用,但在更复杂的应用中,推荐使用 addEventListener 方法来附加事件监听器,因为它提供了更灵活和可维护的代码结构。例如:
    // 获取按钮元素
    const searchButton = document.querySelector('button[onclick="searchJobs()"]');
    // 移除 inline onclick
    searchButton.removeAttribute('onclick');
    // 添加事件监听器
    searchButton.addEventListener('click', searchJobs);
  5. 结果展示: 本教程将结果直接显示在页面上,这比仅仅在控制台打印更具实用性。在实际项目中,您可能需要更复杂的DOM操作来美化结果的展示。
  6. 性能考虑: 对于大型数据集,简单的 forEach 循环可能效率不高。可以考虑使用 Array.prototype.filter() 方法,它能更简洁地表达过滤逻辑,并且在某些情况下可能更优化。

通过本教程,您应该已经掌握了如何将HTML用户输入与JavaScript函数相结合,实现动态数据过滤的核心机制。这一技能是构建交互式Web应用的基础。

热门AI工具

更多
DeepSeek
DeepSeek

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

豆包大模型
豆包大模型

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

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

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

文心一言
文心一言

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

讯飞写作
讯飞写作

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

即梦AI
即梦AI

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

ChatGPT
ChatGPT

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

相关专题

更多
string转int
string转int

在编程中,我们经常会遇到需要将字符串(str)转换为整数(int)的情况。这可能是因为我们需要对字符串进行数值计算,或者需要将用户输入的字符串转换为整数进行处理。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

463

2023.08.02

php中foreach用法
php中foreach用法

本专题整合了php中foreach用法的相关介绍,阅读专题下面的文章了解更多详细教程。

75

2025.12.04

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

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

298

2023.08.03

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

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

212

2023.09.04

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

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

1502

2023.10.24

字符串介绍
字符串介绍

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

624

2023.11.24

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

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

633

2024.03.22

php中定义字符串的方式
php中定义字符串的方式

php中定义字符串的方式:单引号;双引号;heredoc语法等等。想了解更多字符串的相关内容,可以阅读本专题下面的文章。

589

2024.04.29

java入门学习合集
java入门学习合集

本专题整合了java入门学习指南、初学者项目实战、入门到精通等等内容,阅读专题下面的文章了解更多详细学习方法。

1

2026.01.29

热门下载

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

精品课程

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

共58课时 | 4.3万人学习

TypeScript 教程
TypeScript 教程

共19课时 | 2.5万人学习

Bootstrap 5教程
Bootstrap 5教程

共46课时 | 3.1万人学习

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

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