下拉表单点击提交按钮跳转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>
问题根源
- 函数没执行:你定义了
handleFormSubmit函数,但从来没调用它!表单的提交事件监听器根本没绑定上去,点提交当然没反应。 - HTML有语法错:原HTML代码被多余的反引号包裹,浏览器解析不了正确的表单结构。
- 跳转写法不规范:直接用
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
相关产品推荐
相关产品推荐

