使用 jQuery 中的切换按钮隐藏某些输入并显示其他输入

Hide certain inputs and show others using a switch button in jQuery

你好 Whosebug 社区,希望你做得很好,我想做的是当我单击切换按钮时我希望它隐藏某些输入并显示其他输入,我的代码是一个添加学生的表单和老师们,因为有 cummon 输入,所以当我按下开关按钮时,我很难隐藏 uncummon 输入,当我再次单击它时,执行相反的操作,但所有这些似乎都失败了,我只能隐藏一些,当我再次单击它时它不会起作用,这是我所做的:

Jquery代码:

$(document).ready(function(){
    $('.teacher').hide();
    $('.switch').click(function(){
        $('.student').hide();
        $('.teacher').show();
    });
});

HTML代码:

 <label>Student&nbsp;</label>
                                    <label class="switch">
                                      <input type="checkbox" id="switchVal" value="0">
                                      <span class="slider"></span>
                                    </label> 
                                    <label>&nbsp;Teacher</label>

$('.teacher').hide();
  $('.switch').click(function() {
    $('.student').toggle();
    $('.teacher').toggle();
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='student'>Student</div>
<div class="switch">
  <input type="checkbox" id="switchVal" value="0">
  <span class="slider"></span>
</div>
<div class='teacher'>Teacher</div>

使用$(".teacher, .student").toggle();
或者,如果需要,为了更精细的控制,您始终可以使用

获取当前复选框状态
const isChecked = this.checked; // boolean`

示例:

jQuery($ => {

  $(".teacher").hide();
  
  $("#switchVal").on("input", function() {
    $(".teacher, .student").toggle();
  });

});
.toggler {
  display: inline-flex;
  gap: 0 5px;
  cursor: pointer;
}
.toggler-checkbox {
  display: inline-block;
  width: 35px;
  height: 15px;
  background: #444;
  border-radius: 1.2em;
}
.toggler-checkbox::before {
  content: "";
  position: relative;
  display: inline-block;
  width: 15px;
  height: 15px;
  background: #0bf;
  border-radius: 1em;
  transition: transform 0.3s;
}
.toggler input:checked ~ .toggler-checkbox::before {
  transform: translateX(20px);
}
.toggler-label {
  user-select: none;
}
.toggler-label:nth-of-type(1) {
  order: -1;
  color: #0bf;
}
.toggler input:checked ~ .toggler-label:nth-of-type(1) {
  color: inherit;
}
.toggler input:checked ~ .toggler-label:nth-of-type(2) {
  color: #0bf;
}
<label class="toggler">
  <input type="checkbox" id="switchVal" value="0" hidden>
  <span class="toggler-checkbox"></span>
  <b class="toggler-label">Student</b>
  <b class="toggler-label">Teacher</b>
</label>

<ul>
  <li class="student">Student: Anna</li>
  <li class="student">Student: John</li>
  <li class="teacher">Teacher: Mark</li>
  <li class="student">Student: Tara</li>
  <li class="teacher">Teacher: Zack</li>
</ul>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>