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

JavaScript与HTML输入交互:实现动态数据筛选

聖光之護
发布: 2025-11-11 16:59:11
原创
954人浏览过

JavaScript与HTML输入交互:实现动态数据筛选

本教程旨在指导开发者如何利用javascript获取html输入框的值,并通过按钮事件触发数据筛选功能。文章详细介绍了document.getelementbyid().value的用法,以及如何将用户输入传递给javascript函数进行数据处理,从而实现动态、交互式的搜索体验,并强调了大小写转换在搜索中的重要性。

在现代网页应用中,用户输入是实现动态交互的关键。本教程将详细讲解如何通过JavaScript获取HTML表单输入框(input元素)的值,并结合按钮点击事件,对预定义的数据集进行筛选和展示。我们将以一个职位搜索功能为例,演示这一过程。

1. 准备HTML结构

首先,我们需要构建用户界面,包括两个文本输入框用于输入职位名称和地点,以及一个按钮用于触发搜索。同时,为了展示搜索结果,我们还需要一个容器元素。

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>动态职位搜索</title>
    <style>
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; margin: 20px; background-color: #f4f7f6; color: #333; }
        h1 { color: #2c3e50; }
        form { background-color: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); margin-bottom: 20px; }
        input[type="text"] { padding: 10px; margin-right: 10px; border: 1px solid #ccc; border-radius: 4px; width: 200px; box-sizing: border-box; }
        button { padding: 10px 20px; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; transition: background-color 0.3s ease; }
        button:hover { background-color: #0056b3; }
        #results { margin-top: 20px; }
        .job-item { background-color: #e9ecef; border: 1px solid #dee2e6; padding: 15px; margin-bottom: 10px; border-radius: 6px; }
        .job-item strong { color: #0056b3; }
        .no-results { color: #dc3545; font-style: italic; }
        .summary { font-weight: bold; margin-top: 15px; color: #28a745; }
    </style>
</head>
<body>
    <h1>职位搜索</h1>
    <form>
        <input type="text" id="title" placeholder="请输入职位名称">
        <input type="text" id="locationInput" placeholder="请输入地点">
        <button type="button" onclick="searchAndDisplayJobs()">搜索</button>
    </form>
    <div id="results"></div>

    <script src="script.js"></script>
</body>
</html>
登录后复制

请注意,我们将JavaScript代码放在一个单独的文件 script.js 中,并在HTML底部通过 <script src="script.js"></script> 引入,这是一种良好的实践,有助于分离结构和行为。

2. 定义数据源

在JavaScript中,我们需要一个包含职位信息的数组作为数据源。每个职位对象应包含 title(职位名称)和 location(地点)属性。

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

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

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

腾讯智影-AI数字人 73
查看详情 腾讯智影-AI数字人
// 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",
  },
];
登录后复制

3. 实现搜索逻辑

现在,我们将编写 searchAndDisplayJobs() 函数。这个函数将在用户点击“搜索”按钮时执行,负责获取输入值、筛选数据并更新页面。

3.1 获取用户输入

使用 document.getElementById('id') 方法可以获取到HTML元素,然后通过 .value 属性可以获取该输入框的当前值。为了实现大小写不敏感的搜索,我们通常会将获取到的值转换为小写,即使用 .toLowerCase() 方法。

// script.js (接上文)

function searchAndDisplayJobs() {
    // 获取职位名称输入框的值并转换为小写
    const titleQuery = document.getElementById('title').value.toLowerCase();
    // 获取地点输入框的值并转换为小写
    const locationQuery = document.getElementById('locationInput').value.toLowerCase();

    // 获取用于显示结果的DOM元素
    const resultsDiv = document.getElementById('results');
    // 在每次搜索前清空上次的结果,避免重复显示
    resultsDiv.innerHTML = '';

    let count = 0; // 记录找到的职位数量
    const matchingJobs = []; // 存储匹配的职位

    // 遍历所有职位数据进行筛选
    jobs.forEach(job => {
        const lowercaseTitle = job.title.toLowerCase();
        const lowercaseLocation = job.location.toLowerCase();

        // 判断职位标题和地点是否包含用户输入
        if (lowercaseTitle.includes(titleQuery) && lowercaseLocation.includes(locationQuery)) {
            matchingJobs.push(job);
            count++;
        }
    });

    // 根据筛选结果更新页面
    if (matchingJobs.length > 0) {
        matchingJobs.forEach(job => {
            const jobElement = document.createElement('div');
            jobElement.className = 'job-item'; // 添加样式类
            jobElement.innerHTML = `
                <p><strong>职位:</strong> ${job.title}</p>
                <p><strong>地点:</strong> ${job.location}</p>
            `;
            resultsDiv.appendChild(jobElement);
        });
    } else {
        resultsDiv.innerHTML = '<p class="no-results">未找到匹配的职位。</p>';
    }

    // 显示搜索结果摘要
    const summaryElement = document.createElement('p');
    summaryElement.className = 'summary';
    summaryElement.textContent = `共找到 ${count} 个匹配职位。`;
    resultsDiv.appendChild(summaryElement);
}
登录后复制

3.2 完整示例代码

将上述HTML和JavaScript代码结合起来,即可实现完整的动态职位搜索功能。

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>动态职位搜索</title>
    <style>
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; margin: 20px; background-color: #f4f7f6; color: #333; }
        h1 { color: #2c3e50; }
        form { background-color: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); margin-bottom: 20px; }
        input[type="text"] { padding: 10px; margin-right: 10px; border: 1px solid #ccc; border-radius: 4px; width: 200px; box-sizing: border-box; }
        button { padding: 10px 20px; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; transition: background-color 0.3s ease; }
        button:hover { background-color: #0056b3; }
        #results { margin-top: 20px; }
        .job-item { background-color: #e9ecef; border: 1px solid #dee2e6; padding: 15px
登录后复制

以上就是JavaScript与HTML输入交互:实现动态数据筛选的详细内容,更多请关注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号