You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过document.getElementById实现输入后获取职位标题与地点?

解决方案

完整实现代码

HTML 结构

<!-- 搜索表单 -->
<div class="job-search-bar">
  <input type="text" id="titleInput" placeholder="输入职位关键词">
  <input type="text" id="locationInput" placeholder="输入地点关键词">
  <button id="searchBtn">筛选职位</button>
</div>

<!-- 结果展示区 -->
<div id="jobResult"></div>

JavaScript 逻辑

// 模拟职位数据源
const jobData = [
  { title: "前端开发工程师", location: "北京" },
  { title: "后端架构师", location: "上海" },
  { title: "产品经理", location: "深圳" },
  { title: "UI/UX设计师", location: "北京" },
  { title: "测试工程师", location: "上海" }
];

// 获取页面元素
const titleInput = document.getElementById('titleInput');
const locationInput = document.getElementById('locationInput');
const searchBtn = document.getElementById('searchBtn');
const resultBox = document.getElementById('jobResult');

// 职位筛选函数
function findJobs(titleKeyword, locationKeyword) {
  // 转小写实现不区分大小写匹配
  const lowTitle = titleKeyword.toLowerCase();
  const lowLocation = locationKeyword.toLowerCase();

  // 筛选同时匹配标题和地点的职位
  return jobData.filter(job => {
    return job.title.toLowerCase().includes(lowTitle) && job.location.toLowerCase().includes(lowLocation);
  });
}

// 绑定按钮点击事件
searchBtn.addEventListener('click', () => {
  // 获取输入框值,去除首尾空格
  const titleVal = titleInput.value.trim();
  const locationVal = locationInput.value.trim();

  // 调用筛选函数
  const matchedJobs = findJobs(titleVal, locationVal);

  // 渲染结果到页面
  showResults(matchedJobs);
});

// 结果渲染辅助函数
function showResults(jobs) {
  if (jobs.length === 0) {
    resultBox.innerHTML = '<p>未找到匹配的职位</p>';
    return;
  }

  const jobList = jobs.map(job => `<li>${job.title} - ${job.location}</li>`).join('');
  resultBox.innerHTML = `<ul>${jobList}</ul>`;
}

核心要点说明

  • 获取输入值:通过document.getElementById('元素ID')拿到输入框元素后,直接访问.value属性即可获取用户输入内容,用.trim()去掉首尾空格避免无效匹配。
  • 筛选逻辑:findJobs函数接收两个关键词参数,通过filter遍历数据源,结合includes实现模糊匹配,转小写确保匹配不区分大小写。
  • 结果渲染:将筛选后的职位数据生成HTML结构插入页面,无匹配结果时给出明确提示。

内容的提问来源于stack exchange,提问作者Mike Youlend

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 20:18:18