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

如何制作可拼接站点URL与输入内容的搜索按钮,支持隐藏.html后缀

问题原因

原生form的GET提交方式会自动将带有name属性的表单项值拼接为查询参数,追加到action配置的地址后,你给输入框设置了name="n",所以提交后URL会出现多余的?n=参数。

解决方案

通过JS拦截表单提交事件,手动处理输入内容后跳转即可,完整代码如下:

<form class="test" role="search">
  <input type="search" id="testSearch" class="Search" placeholder="Search Here...">
  <button type="submit">搜索</button>
</form>
<script>
const searchForm = document.querySelector('.test')
const baseSite = 'https://mysitename.com'

searchForm.addEventListener('submit', function(e) {
  // 阻止表单默认提交行为
  e.preventDefault()
  const inputContent = document.getElementById('testSearch').value.trim()
  if (!inputContent) return

  // 自动补全.html后缀
  const finalPath = inputContent.endsWith('.html') ? inputContent : `${inputContent}.html`
  // 直接跳转到目标地址
  window.location.href = `${baseSite}/${finalPath}`
})
</script>

实现效果

  • 输入abcd123.html点击提交,精准跳转至https://mysitename.com/abcd123.html
  • 输入abcd123点击提交,自动补全后缀跳转同一地址
  • 不会生成多余的查询参数

如果你的站点已经配置了服务端路径重写规则,支持直接访问不带.html后缀的地址加载对应资源,删除代码里的后缀补全逻辑即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 05:18:03