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

多步骤表单分步显示问题求助:逐fieldset展示后切换section

解决多步骤表单的Section切换问题

我明白你的需求了——要先把当前Section里的所有Fieldset逐个走完,再切换到下一个Section,而不是跨Section直接跳Fieldset。原来的代码只处理了Fieldset的同级切换,没考虑Section的层级关系,所以遇到Section边界就卡住了。下面给你调整后的完整方案:

1. 调整CSS规则

首先修改CSS,确保初始状态只显示第一个Section的第一个Fieldset,其他Section和Fieldset都隐藏:

#form section { display: none; }
#form section:first-of-type { display: block; }
#form fieldset { display: none; }
#form section:first-of-type fieldset:first-of-type { display: block; }

2. 重写jQuery逻辑

我们需要分别跟踪当前所在的Section和该Section内的Fieldset位置,点击Next时先判断当前Section是否还有未完成的Fieldset,再决定是切换Fieldset还是切换Section:

// 初始化跟踪变量:当前Section索引、当前Section内的Fieldset索引、总步骤数
let currentSectionIdx = 0;
let currentFieldsetIdx = 0;
const sections = $("#form section");
const totalSteps = $("fieldset").length;
let currentStep = 1;

// 初始化进度条
setProgressBar(currentStep);

$(".next").click(function() {
  const currentSection = sections.eq(currentSectionIdx);
  const sectionFieldsets = currentSection.find("fieldset");

  // 情况1:当前Section还有下一个Fieldset
  if (currentFieldsetIdx < sectionFieldsets.length - 1) {
    sectionFieldsets.eq(currentFieldsetIdx).hide();
    currentFieldsetIdx++;
    sectionFieldsets.eq(currentFieldsetIdx).show();
  } 
  // 情况2:当前Section的Fieldset已走完,检查是否有下一个Section
  else if (currentSectionIdx < sections.length - 1) {
    // 隐藏当前Section
    currentSection.hide();
    currentSectionIdx++;
    // 显示下一个Section并重置Fieldset索引
    const nextSection = sections.eq(currentSectionIdx);
    nextSection.show();
    currentFieldsetIdx = 0;
    nextSection.find("fieldset").eq(currentFieldsetIdx).show();
  } 
  // 情况3:所有Section和Fieldset都完成了
  else {
    alert("表单已全部完成!");
    // 这里可以添加表单提交逻辑
    return;
  }

  // 更新进度条
  currentStep++;
  setProgressBar(currentStep);
});

// 进度条更新函数保持不变
function setProgressBar(curStep) {
  const percent = parseFloat(100 / totalSteps) * curStep;
  $(".progress-bar")
    .css("width", `${percent.toFixed()}%`)
    .text(`${percent.toFixed()}%`);
}

代码关键点说明

  • 新增currentSectionIdx和currentFieldsetIdx两个变量,分别记录当前所在的Section和该Section内的Fieldset位置,解决了层级切换的问题
  • 点击Next按钮时的逻辑分支清晰:先处理同Section内的Fieldset切换,再处理Section间的切换,最后处理表单完成的情况
  • 进度条依然基于所有Fieldset的总数计算,保证进度显示准确

这样修改后,不管你通过GET请求生成多少个Section,表单都会先走完当前Section的所有Fieldset,再自动切换到下一个Section的第一个Fieldset啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:42:20