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

如何根据HTML表单提交的用户选择,重定向到网站根目录下的对应页面?

实现表单提交后的页面重定向

要根据用户选择的选项跳转到网站根目录下的对应页面,你需要完成两个关键操作:

1. 阻止表单默认提交行为

表单默认会触发页面刷新或提交请求,所以第一步要在提交函数里先阻止这个默认动作,避免干扰跳转逻辑。

2. 使用页面跳转API实现定向

JavaScript里常用window.location.href或location.assign()来跳转页面,根目录下的页面直接用/页面文件名的路径即可。

完整修正后的代码

<form onsubmit="submitForm(event)">
    <p> Do you like cats or dogs </p>
    <input type="radio" id="cat" value="Cats" name="pet">
    <label for="cat">Cats</label>
    <input type="radio" id="dog" value="Dogs" name="pet">
    <label for="dog">Dogs</label><br>
    <button>Submit</button>
</form>
<script>
    function submitForm(event) {
        // 阻止表单默认提交行为
        event.preventDefault();
        
        if(document.getElementById('cat').checked) {
            // 跳转到根目录下的cat页面
            window.location.href = '/cat.html';
        }else if(document.getElementById('dog').checked) {
            // 跳转到根目录下的dog页面
            window.location.href = '/dog.html';
        } else {
            // 可选:处理用户未选择任何选项的情况
            alert('请选择一个选项!');
        }
    }
</script>

补充说明

  • 给单选框加上相同的name属性,确保它们互斥(用户只能选一个),你原来的代码遗漏了这个属性,补上后功能更规范。
  • 如果想要允许用户通过浏览器后退按钮回到当前页面,也可以把window.location.href换成location.assign('/cat.html'),两者效果基本一致,assign()更强调“导航”语义。
  • 如果需要立即替换当前页面历史记录(用户无法后退),可以用window.location.replace('/cat.html'),不过一般场景下用前两种就足够。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 00:24:17