首页 > web前端 > js教程 > 正文

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

霞舞
发布: 2025-11-11 11:33:02
原创
270人浏览过

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

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

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

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

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

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>职位搜索器</title>
</head>
<body>
    <form>
        <input type="text" id="titleInput" placeholder="请输入职位名称">
        <input type="text" id="locationInput" placeholder="请输入地点">
        <button type="button" onclick="searchJobs()">搜索</button>
    </form>
    <div id="results">
        <!-- 搜索结果将显示在这里 -->
    </div>

    <script src="script.js"></script>
</body>
</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 属性。

腾讯智影-AI数字人
腾讯智影-AI数字人

基于AI数字人能力,实现7*24小时AI数字人直播带货,低成本实现直播业务快速增增,全天智能在线直播

腾讯智影-AI数字人 73
查看详情 腾讯智影-AI数字人

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

// 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 = '<p>未找到匹配的职位。</p>';
    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表单元素(如 <input>、<textarea>、<select>)的一个属性,用于获取或设置该元素的当前值。
  • searchJobs() 函数负责:
    1. 通过ID获取两个输入框元素。
    2. 读取它们的 .value 属性,获取用户输入的字符串。
    3. 将这些值作为参数传递给 findJobs 函数。
    4. 调用 displayResults 函数,将筛选出的职位列表呈现在页面上,而不是只在控制台输出。这样用户才能直观地看到结果。

完整代码示例

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

index.html:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>职位搜索器</title>
    <style>
        body { font-family: sans-serif; margin: 20px; }
        input { margin-right: 10px; padding: 8px; border: 1px solid #ccc; border-radius: 4px; }
        button { padding: 8px 15px; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; }
        button:hover { background-color: #0056b3; }
        #results { margin-top: 20px; border-top: 1px solid #eee; padding-top: 15px; }
        #results ul { list-style: none; padding: 0; }
        #results li { background-color: #f9f9f9; margin-bottom: 5px; padding: 10px; border-radius: 4px; }
    </style>
</head>
<body>
    <h1>职位搜索</h1>
    <form>
        <input type="text" id="titleInput" placeholder="请输入职位名称">
        <input type="text" id="locationInput" placeholder="请输入地点">
        <button type="button" onclick="searchJobs()">搜索</button>
    </form>
    <div id="results">
        <!-- 搜索结果将显示在这里 -->
    </div>

    <script src="script.js"></script>
</body>
</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 = '<p>未找到匹配的职位。</p>';
    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应用的基础。

以上就是将HTML输入与JavaScript函数连接以实现数据过滤的详细内容,更多请关注php中文网其它相关文章!

HTML速学教程(入门课程)
HTML速学教程(入门课程)

HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!

下载
来源: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号