如何实现单选按钮结合提交按钮跳转至本地HTML文件
解决方案
现有代码的问题
- 缺少
<form>标签包裹单选按钮和提交按钮,导致JS监听的form.submit事件无法触发 - 第二个换行标签语法错误(
<br未闭合) - 单选按钮上的
onclick="Form()"无意义,且Form()函数未定义,会引发控制台报错
修正后的完整代码
<form id="userTypeForm"> <input type="radio" name="userType" value="signup-customer.html">Client<br> <input type="radio" name="userType" value="signup-provider.html">Provider<br> <input type="radio" name="userType" value="signup-supervisor.html">Supervisor<br> <button type="submit">提交</button> </form> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(function(){ $("#userTypeForm").submit(function(e) { e.preventDefault(); // 获取选中的单选按钮值 const targetUrl = $(this).find('input[type="radio"]:checked').val(); // 校验是否选中了选项,避免无选择时跳转错误 if(targetUrl) { window.location.href = targetUrl; } else { alert("请选择用户类型"); } }); }); </script>
代码说明
- 用
<form>标签包裹所有表单元素,并给form设置ID,方便精准选择 - 移除了多余的
onclick事件,避免不必要的错误 - 增加了选中校验,当用户未选择任何选项时弹出提示,防止无效跳转
- 使用
window.location.href替代window.location,语义更清晰,兼容性一致
内容的提问来源于stack exchange,提问作者Mohamed Ali
相关产品推荐
相关产品推荐

