
本教程详细介绍了如何通过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() 函数,它将在按钮被点击时执行。
// 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() 函数负责:
- 通过ID获取两个输入框元素。
- 读取它们的 .value 属性,获取用户输入的字符串。
- 将这些值作为参数传递给 findJobs 函数。
- 调用 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);
}注意事项与最佳实践
- ID的唯一性: document.getElementById() 依赖于ID的唯一性。确保您的HTML文档中每个元素的ID都是独一无二的。
- 大小写处理: 在进行字符串比较时,通常建议将所有字符串转换为相同的大小写(例如,都转换为小写),以实现不区分大小写的搜索,提高用户体验。本教程在 findJobs 函数内部处理了这一逻辑。
- 输入验证: 在实际应用中,您可能需要对用户输入进行验证,例如检查输入是否为空,或者是否符合特定的格式要求。
-
事件监听器: 尽管 onclick 属性简单易用,但在更复杂的应用中,推荐使用 addEventListener 方法来附加事件监听器,因为它提供了更灵活和可维护的代码结构。例如:
// 获取按钮元素 const searchButton = document.querySelector('button[onclick="searchJobs()"]'); // 移除 inline onclick searchButton.removeAttribute('onclick'); // 添加事件监听器 searchButton.addEventListener('click', searchJobs); - 结果展示: 本教程将结果直接显示在页面上,这比仅仅在控制台打印更具实用性。在实际项目中,您可能需要更复杂的DOM操作来美化结果的展示。
- 性能考虑: 对于大型数据集,简单的 forEach 循环可能效率不高。可以考虑使用 Array.prototype.filter() 方法,它能更简洁地表达过滤逻辑,并且在某些情况下可能更优化。
通过本教程,您应该已经掌握了如何将HTML用户输入与JavaScript函数相结合,实现动态数据过滤的核心机制。这一技能是构建交互式Web应用的基础。











