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

下拉表单点击提交按钮跳转URL功能失效问题求助

下拉表单提交后不跳转?看这几个修复点

问题情况

做了个带两个选项的下拉表单,本来想点提交按钮时跳转到选中选项对应的URL,但点了提交完全没反应。用的JS和HTML代码如下:

JS代码:

function handleFormSubmit() {
 var form = document.querySelector("form");
form.addEventListener("submit", function(event) {
event.preventDefault();
var destination = document.getElementById("destination");
location = destination.options[destination.selectedIndex].value;
});
}

HTML代码:

<form action="" method="post">
  <label for="destination">Travelling to:</label>
  <select id="destination" name="destination">
    <option value="https://nstcprep.blogspot.com/">Destination 1</option>
    <option value="https://nstcprep.blogspot.com/">Destination 2</option>
  </select>
  <input type="submit" value="Submit">
</form>

问题根源

  1. 函数没执行:你定义了handleFormSubmit函数,但从来没调用它!表单的提交事件监听器根本没绑定上去,点提交当然没反应。
  2. HTML有语法错:原HTML代码被多余的反引号包裹,浏览器解析不了正确的表单结构。
  3. 跳转写法不规范:直接用location赋值虽然偶尔能生效,但标准写法是window.location.href,能避免全局变量冲突的坑。

修复步骤

1. 修正HTML代码

删掉包裹表单的多余反引号,确保HTML结构正常。

2. 调用绑定事件的函数

要么直接在JS代码末尾加handleFormSubmit();,要么等DOM加载完再绑定(更稳妥),比如用DOMContentLoaded事件。

3. 规范跳转语句

把location = ...换成window.location.href = ...。

修改后的完整代码

方案一:直接调用函数

<form action="" method="post">
  <label for="destination">Travelling to:</label>
  <select id="destination" name="destination">
    <option value="https://nstcprep.blogspot.com/">Destination 1</option>
    <option value="https://nstcprep.blogspot.com/">Destination 2</option>
  </select>
  <input type="submit" value="Submit">
</form>

<script>
function handleFormSubmit() {
  var form = document.querySelector("form");
  form.addEventListener("submit", function(event) {
    event.preventDefault();
    var destination = document.getElementById("destination");
    window.location.href = destination.options[destination.selectedIndex].value;
  });
}

// 调用函数绑定事件
handleFormSubmit();
</script>

方案二:DOM加载完成后绑定(更推荐)

<form action="" method="post">
  <label for="destination">Travelling to:</label>
  <select id="destination" name="destination">
    <option value="https://nstcprep.blogspot.com/">Destination 1</option>
    <option value="https://nstcprep.blogspot.com/">Destination 2</option>
  </select>
  <input type="submit" value="Submit">
</form>

<script>
// 等页面DOM元素都加载完再绑定事件
document.addEventListener('DOMContentLoaded', function() {
  var form = document.querySelector("form");
  form.addEventListener("submit", function(event) {
    event.preventDefault();
    var destination = document.getElementById("destination");
    window.location.href = destination.options[destination.selectedIndex].value;
  });
});
</script>

改完之后,点提交按钮就能正常跳转到选中的URL了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 21:05:13