
本教程详细介绍了如何通过JavaScript获取HTML输入框中的用户数据,并将其传递给JavaScript函数以实现数据过滤功能。我们将通过一个具体的职位搜索案例,演示如何使用document.getElementById().value获取输入值,处理大小写不敏感的搜索,并动态地根据用户输入筛选数据。
在现代Web应用开发中,与用户交互并根据其输入动态处理数据是一项基本且重要的能力。本教程将引导您完成一个常见场景:从HTML表单的输入框中获取用户输入的文本,并将其作为参数传递给JavaScript函数,进而对预定义的数据集进行筛选。我们将以一个职位搜索应用为例,展示如何实现这一功能。
首先,我们需要在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免费学习笔记(深入)”;
接下来,我们定义一个职位数据集,并编写一个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免费学习笔记(深入)”;
现在,最关键的一步是获取用户在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 = '<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免费学习笔记(深入)”;
将上述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);
}// 获取按钮元素
const searchButton = document.querySelector('button[onclick="searchJobs()"]');
// 移除 inline onclick
searchButton.removeAttribute('onclick');
// 添加事件监听器
searchButton.addEventListener('click', searchJobs);通过本教程,您应该已经掌握了如何将HTML用户输入与JavaScript函数相结合,实现动态数据过滤的核心机制。这一技能是构建交互式Web应用的基础。
以上就是将HTML输入与JavaScript函数连接以实现数据过滤的详细内容,更多请关注php中文网其它相关文章!
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号