首页 > 解决方案 > 查找数据属性和复选框子项

问题描述

我希望你能看到我在这里想要做什么。我试图为 div 保持相同的结构,但单击顶部区域中的全选仅选择这 3 个,而底部全选仅选择底部 3。

显然有更好的方法可以做到这一点,但我已将我的代码剥离回这个基本示例。请帮我重写这一行:

$("div").find("[data-profile-id='"+profileID+"']").find(".score_alert_cb1").each(function() {

所以我可以使用 profile-id 数据属性来选择该 div 内的复选框。

谢谢

$('.profile #select_all_cb').click(function() {
  var profileID = $(this).closest('.profile').data('profile-id');
  if($(this).is(":checked")) {
      $("div").find("[data-profile-id='"+profileID+"']").find(".score_alert_cb1").each(function() {
          $(this).prop('checked', true);
      });
  } else {
      $("div").find("[data-profile-id='"+profileID+"']").find(".score_alert_cb1").each(function() { //Check all boxes
          $(this).prop('checked', false);
      });
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="profile" data-profile-id="1">
   <div>
      A lot of data before my checkbox
    </div>
    <div>
    <input type="checkbox" id="select_all_cb">select all
    </div>
    <div>
       <input type="checkbox" class="score_alert_cb1">
       <input type="checkbox" class="score_alert_cb1">
       <input type="checkbox" class="score_alert_cb1">
    </div>
 </div>
 <br /><br />
 <div class="profile" data-profile-id="2">
   <div>
      A lot of data before my checkbox
    </div>
    <div>
    <input type="checkbox" id="select_all_cb">select all
    </div>
    <div>
       <input type="checkbox" class="score_alert_cb1">
       <input type="checkbox" class="score_alert_cb1">
       <input type="checkbox" class="score_alert_cb1">
    </div>
 </div>

标签: javascriptjqueryhtml

解决方案


ID 是唯一的,因此更改id="select_all_cb"class="select_all_cb".

单击.select_all_cb时,向上查找.profile父级,将复选框值作为布尔值存储在isChecked变量中,并找到.score_alert_cb1当前.profile元素中的所有复选框。

$(".profile .select_all_cb").click(function() {
  var profile = $(this).closest(".profile");
  // var profileID = profile.data('profile-id');
  var isChecked = $(this).is(":checked");
  profile.find(".score_alert_cb1").prop("checked", isChecked);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="profile" data-profile-id="1">
   <div>
      A lot of data before my checkbox
    </div>
    <div>
    <input type="checkbox" class="select_all_cb">select all
    </div>
    <div>
       <input type="checkbox" class="score_alert_cb1">
       <input type="checkbox" class="score_alert_cb1">
       <input type="checkbox" class="score_alert_cb1">
    </div>
 </div>
 <br /><br />
 <div class="profile" data-profile-id="2">
   <div>
      A lot of data before my checkbox
    </div>
    <div>
    <input type="checkbox" class="select_all_cb">select all
    </div>
    <div>
       <input type="checkbox" class="score_alert_cb1">
       <input type="checkbox" class="score_alert_cb1">
       <input type="checkbox" class="score_alert_cb1">
    </div>
 </div>


推荐阅读