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

如何实现HTML搜索提交按钮跳转至带搜索关键词的目录

实现自定义路径的HTML搜索表单方案

要实现你需要的这种搜索跳转效果,核心是把输入的关键词作为URL路径的一部分,而非默认的查询参数形式。下面是具体的实现代码和说明:

基础实现代码

<form id="searchForm">
  <input type="text" id="searchKeyword" placeholder="输入搜索关键词" required>
  <button type="submit">搜索</button>
</form>

<script>
document.getElementById('searchForm').addEventListener('submit', function(e) {
  // 阻止表单默认的GET提交行为
  e.preventDefault();
  
  // 获取并去除关键词首尾空格
  const keyword = document.getElementById('searchKeyword').value.trim();
  
  // 空关键词不执行跳转
  if (!keyword) return;
  
  // 对关键词做URL编码,兼容空格、特殊字符
  const encodedKeyword = encodeURIComponent(keyword);
  
  // 跳转到目标搜索路径
  window.location.href = `https://website.org/search/${encodedKeyword}`;
});
</script>

关键细节说明

  • required 属性:让浏览器自动校验输入框不为空,避免空关键词跳转
  • encodeURIComponent():处理关键词里的空格、特殊字符(如&、%),确保URL格式合法
  • 阻止默认提交:避免表单把关键词以?search=xxx的形式附加到URL后,完全自定义路径结构

可选优化

如果需要把关键词里的空格替换成连字符(比如输入"john doe"跳转到/search/john-doe),可以修改JS逻辑:

document.getElementById('searchForm').addEventListener('submit', function(e) {
  e.preventDefault();
  const keyword = document.getElementById('searchKeyword').value.trim();
  if (!keyword) return;
  
  // 把空格替换为连字符(按需调整规则)
  const processedKeyword = keyword.replace(/\s+/g, '-');
  const encodedKeyword = encodeURIComponent(processedKeyword);
  
  window.location.href = `https://website.org/search/${encodedKeyword}`;
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 09:52:04