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

如何使用jQuery实现两个表单间切换 现有代码不显示form2如何修复

问题排查

  • 语法错误:变量声明语句中错误使用逗号连接$form2.hide()方法,导致初始隐藏form2的逻辑未执行,同时代码存在语法隐患
  • 逻辑错误:切换时的判断条件和显示隐藏逻辑完全倒置,没有触发form2显示的分支
  • 事件选择不合理:checkbox使用click事件容易出现状态和动作不同步的问题,更适合用change事件监听状态变更

修复后代码

JS代码

$(document).ready(function() {
  var $form1 = $('#form1'),
    $form2 = $('#form2');
  // 页面加载完成默认隐藏form2
  $form2.hide();

  $("#customSwitch1").change(function() {
    // 根据复选框选中状态切换表单
    if ($(this).prop('checked')) {
      $form1.hide();
      $form2.show();
    } else {
      $form1.show();
      $form2.hide();
    }
  });
});

CSS代码(原有逻辑无问题可直接保留)

/* The switch - the box around the slider */
#customSwitch1 {
  position: relative;
  display: inline-block;
  width: 15px;
  height: 10px;
}

HTML代码(原有结构无问题可直接保留)

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="custom-control custom-switch">
  <input type="checkbox" class="custom-control-input" id="customSwitch1">
  <label class="custom-control-label" for="customSwitch1">
    <h6>Switch to form2</h6>
  </label>
</div>

<form id='form1' name='form1' method="" action="">
  <input type="text">
</form>

<form id='form2' name='form2' method="" action="">
  <input type="text">
</form>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 21:36:04