如何使用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
相关产品推荐
相关产品推荐

