首页 > 解决方案 > 如何启用在页面加载时选中的第一个复选框并仅显示数据目标 div 并隐藏其他数据,并且一次仅选中一个复选框

问题描述

  1. 如何启用在页面加载时选中的第一个复选框,该复选框仅显示针对数据的 div 并隐藏其他 div(即默认选中页面加载 DIV1 复选框并仅显示 DIV1 并使用 jQuery first-child 隐藏其他 DIVS)。现在,我的第一个复选框在页面加载时显示已选中,但除非物理检查,否则它会显示页面加载上的所有 div。我只想显示 DIV1 检查显示数据 1 并在页面加载时隐藏其他。

  2. 请问如何使用jQuery一次只检查一个复选框?

  3. 选中复选框时,它应该隐藏其他 DIV 并仅显示它的数据目标 div。

这是我的代码:

$(document).ready(function () {
 $('.my-features').on('click', function () {
    var checkbox = $(this);
    var div = checkbox.data('name');
    if (checkbox.is(':checked')) {

        $('#' + div).show();
    } else {
        $('#' + div).hide();
        $('#' + checkbox.attr('data-name')).hide();
    }
 });    
});

$(document).ready(
 function(){
  $('input:checkbox:first-child').attr('checked',true);
 }
);

<input type="checkbox" data-name="div1" class="my-features" />DIV1
<input type="checkbox" data-name="div2" class="my-features" />DIV2
<input type="checkbox" data-name="div3" class="my-features" />DIV3
<input type="checkbox" data-name="div4" class="my-features" />DIV4
<input type="checkbox" data-name="div5" class="my-features" />DIV5
<input type="checkbox" data-name="div6" class="my-features" />DIV6

<div id="div1">1
</div>
<div id="div2">2
</div>
<div id="div3">3
</div>
<div id="div4">4
</div>
<div id="div5">5
</div>
<div id="div6">6
</div>

由于我对 jQuery 的了解有限,我已尽力使用代码。提前致谢。

标签: htmljquerycheckboxshow-hide

解决方案


只需隐藏除divdoc ready 之外的所有 div。此外,您应该使用changeevent 来表示inputnotclick

要“取消选中”所有其他复选框,以便一次只选中一个复选框(顺便说一句,这就是单选按钮的工作方式,也许您想使用单选按钮?)只需取消选中除正在检查的复选框之外的所有复选框$('.my-features').not(this).prop('checked', false);

您也可以使用将被#${div} 替换template strings的经典连接含义来代替# + div

看看下面的 jquery only 解决方案

*免责声明。添加了一个div因为inputs否则input:first-child将不起作用(在代码段中,我们将<script>标签作为第一个孩子)并在“显示/隐藏”div中添加了一个类

$(document).ready(function() {
  $('input[type="checkbox"]:first-child ').prop('checked', true);
  $("div.text:not(#div1)").hide()

  $('.my-features').on('change', function() {
    var checkbox = $(this);
    var div = checkbox.data('name');
    $('.my-features').not(this).prop('checked', false);  

    if (checkbox.is(':checked')) {
      $("div.text").hide();
      $(`#${div}`).show();
    } else {
      $(`#${div}`).hide();
      
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input type="checkbox" data-name="div1" class="my-features" />DIV1
<input type="checkbox" data-name="div2" class="my-features" />DIV2
<input type="checkbox" data-name="div3" class="my-features" />DIV3
<input type="checkbox" data-name="div4" class="my-features" />DIV4
<input type="checkbox" data-name="div5" class="my-features" />DIV5
<input type="checkbox" data-name="div6" class="my-features" />DIV6
</div>
<div class="text" id="div1">1
</div>
<div class="text"  id="div2">2
</div>
<div class="text"  id="div3">3
</div>
<div class="text"  id="div4">4
</div>
<div class="text"  id="div5">5
</div>
<div class="text"  id="div6">6
</div>


推荐阅读