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

问卷Next按钮跳转逻辑异常及提交展示结果实现求助

问题分析与修复方案(聚焦男性页面跳转逻辑)

嘿,咱们来一步步搞定这个Next按钮总是跳男性页面的问题~

核心问题拆解

我看了你的代码,发现两个关键问题导致跳转逻辑失效:

  1. Next按钮默认是提交类型:你主页面里的<button id="next">Next</button>没指定type="button",浏览器会默认把它当成type="submit",点击时直接触发表单的submit事件,完全打乱了你写的跳转逻辑。
  2. 事件绑定时机错误:你把Next按钮的点击事件放在了表单的onsubmit回调里,这意味着只有表单提交时才会绑定这个点击事件,时机完全不对——咱们需要页面一加载就绑定好跳转逻辑,而不是等表单提交时才处理。

分步修复方案

1. 修正主页面的Next按钮

先给Next按钮加上type="button",避免它触发表单默认提交行为:

<form id="form1">
  <p>Gender</p>
  <label><input type="radio" name="gender" id="male" value="Male">Male</label>
  <label><input type="radio" name="gender" id="female" value="Female">Female</label>
  <!-- 新增type="button",阻止默认提交 -->
  <button id="next" type="button" value="Next">Next</button>
</form>
<script type="text/javascript" src="script.js"></script>

2. 重构JavaScript代码

把跳转逻辑和表单提交逻辑分开,确保页面加载完成就绑定好事件:

// 等待页面所有元素加载完成再执行逻辑
document.addEventListener('DOMContentLoaded', function() {
  // 处理主页面的Next按钮跳转
  const nextBtn = document.getElementById('next');
  if (nextBtn) {
    nextBtn.onclick = function() {
      const maleRadio = document.getElementById('male');
      const femaleRadio = document.getElementById('female');
      
      if (maleRadio.checked) {
        location.href = "malesection.html";
      } else if (femaleRadio.checked) {
        location.href = "femalesection.html";
      } else {
        // 可选:提示用户先选性别
        alert("Please select your gender first!");
      }
    }
  }

  // 处理男性页面的Submit按钮逻辑
  const maleForm = document.getElementById('form1');
  // 只在男性页面执行这段逻辑
  if (maleForm && window.location.pathname.includes('malesection.html')) {
    maleForm.onsubmit = function(e) {
      // 阻止表单默认提交刷新页面
      e.preventDefault();
      
      const ansEl = document.getElementById("ans");
      const ans2El = document.getElementById("ans2");
      const heightShort = document.getElementById("short");
      const wristSmall = document.getElementById("small");

      // 注意:主页面的性别单选框不会出现在男性页面,你之前的t/a/s单选框也没在代码里看到,记得后续补充或调整逻辑
      // 先处理已有的身高+手腕判断
      if (heightShort.checked && wristSmall.checked) {
        ans2El.innerHTML = "You are a male with short height and small body frame. Thus, you have an Ectomorph body type. Choose clothes that neatly skim the body.";
      } else {
        ans2El.innerHTML = "Please select your height and wrist size!";
      }

      return false;
    }
  }
});

额外小提示

你JS代码里提到的teen/adult/senior单选框在提供的HTML里没出现,会导致控制台报错,记得后续补充对应的HTML元素,或者调整这部分逻辑哦。如果需要在男性页面保留用户选择的性别信息,可以用localStorage来传递——主页面跳转前存性别,男性页面读取即可。

这样修改后,Next按钮就能根据选中的性别正确跳转,男性页面的Submit按钮也能正常展示结果啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 19:02:35