如何检查是否使用jQuery检查了所有兄弟姐妹(包括选中的兄弟姐妹)?

时间:2019-06-14 12:54:23

标签: jquery jquery-selectors

我正在尝试仅获取所选元素的同级元素,但找不到适合此方法或实现该方法的合适方法。我总是用find()方法和children()来获取整棵树。

此点击应类似于复选框树:

如果单击“父级”,则应单击所有子级;如果取消选中“父级”,则必须不选中所有子级。

但是不起作用的是,如果您选中了一个复选框并且未单击所有同级,则父项必须不确定!

上面的父级也必须不确定。

所以我真正需要的是获取选中复选框的父级,然后收集子级并检查是否全部选中。如果是,则将父级设置为选中状态(如果未选中),则父级必须不确定。但是问题是jquery深入了……。我只需要第一个孩子,而不需要下面的所有东西。

$(document).on('change', 'input.parent_cat_0', function() {
  var mainPermission = $(this);
  var mainPermissionChildren = mainPermission.parent().find('input:checkbox');
  if (mainPermission.is(':checked')) {
    mainPermissionChildren.each(function() {
      this.indeterminate = false;
      this.checked = true;
    });
  } else {
    mainPermissionChildren.each(function() {
      this.indeterminate = false;
      this.checked = false;
      $(this).removeClass("displayNone").next("img.tick").remove();
    });
  }
});

$(document).on('change', 'input.docPermission:not(.parent_cat_0)', function() {
  var selected = $(this);
  var liParents = selected.parents('li');
  var allCheckboxes = liParents.find('input:checkbox');
  var childrenOfSelected = selected.parent().find('input:checkbox');
  var upperParents = $(allCheckboxes).not(childrenOfSelected).get();

  if (selected.is(':checked')) {
    childrenOfSelected.prop('indeterminate', false);
    childrenOfSelected.prop('checked', true);

    //console.log('Total upper parents:', upperParents.length);

    $(upperParents).each(function (i,e) {
      // HOW TO GET ONLY FIRST SIBLINGS
      // For example if you click on Form 1
      // you should get only (Form 1a, Form 1b, Form 1c)
      // but NOT 'Form 1aa'
      //console.log($(e));
    });

  } else {
    childrenOfSelected.prop('indeterminate', false);
    childrenOfSelected.prop('checked', false);
  }


});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<li class="main">
  <input type="checkbox" id="cat_52" class="docPermission  parent_cat_0" name="localPerm[]">
  <label class="strong" for="cat_52">Forms</label>
  <ul>
    <li>
      <input type="checkbox" id="cat_53" class="docPermission  parent_cat_52" name="localPerm[]">
      <label class="strong" for="cat_53">Form 1</label>
      <ul>
        <li>
          <input type="checkbox" id="cat_55" class="docPermission  parent_cat_53" name="localPerm[]">
          <label class="strong" for="cat_55">Form 1a</label>
          <ul>
            <li>
              <input type="checkbox" id="cat_56" class="docPermission  parent_cat_55" name="localPerm[]">
              <label class="strong" for="cat_56">Form 1aa</label>
            </li>
          </ul>
        </li>
        <li class="main">
          <input type="checkbox" id="doc_80" class="docPermission  parent_cat_53" name="localPerm[]">
          <label for="doc_80">Form 1b</label>
        </li>
        <li class="main">
          <input type="checkbox" id="doc_82" class="docPermission  parent_cat_53" name="localPerm[]">
          <label for="doc_82">Form 1c</label>
        </li>
      </ul>
    </li>
    <li>
      <input type="checkbox" id="cat_54" class="docPermission  parent_cat_52" name="localPerm[]">
      <label class="strong" for="cat_54">Form 2</label>
    </li>
  </ul>
</li>

2 个答案:

答案 0 :(得分:1)

您可以尝试siblings()andSelf()

$(document).on('change', 'input:checkbox', function(e) {
  const $this = $(this);

  if (!e.isTrigger) {
    $this
      .siblings('ul')
      .find('input:checkbox')
      .prop('checked', this.checked);
  }

  const $children = $this.parent('li').siblings().addBack();
  const $ckb = $children.find('> input:checkbox');

  const total = $ckb.length;
  const checked = $ckb.filter(':checked').length;
  const indeter = $ckb.filter(function() {
    return this.indeterminate;
  }).length;

  $this
    .parents('ul:first')
    .siblings('input:checkbox')
    .prop({
      checked: checked === total,
      indeterminate: indeter > 0 || (checked > 0 && checked < total)
     })
    .trigger('change')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<ul>
  <li class="main">
    <input type="checkbox" id="cat_52" class="docPermission  parent_cat_0" name="localPerm[]">
    <label class="strong" for="cat_52">Forms</label>
    <ul>
      <li>
        <input type="checkbox" id="cat_53" class="docPermission  parent_cat_52" name="localPerm[]">
        <label class="strong" for="cat_53">Form 1</label>
        <ul>
          <li>
            <input type="checkbox" id="cat_55" class="docPermission  parent_cat_53" name="localPerm[]">
            <label class="strong" for="cat_55">Form 1a</label>
            <ul>
              <li>
                <input type="checkbox" id="cat_56" class="docPermission  parent_cat_55" name="localPerm[]">
                <label class="strong" for="cat_56">Form 1aa</label>
              </li>
            </ul>
          </li>
          <li class="main">
            <input type="checkbox" id="doc_80" class="docPermission  parent_cat_53" name="localPerm[]">
            <label for="doc_80">Form 1b</label>
          </li>
          <li class="main">
            <input type="checkbox" id="doc_82" class="docPermission  parent_cat_53" name="localPerm[]">
            <label for="doc_82">Form 1c</label>
          </li>
        </ul>
      </li>
      <li>
        <input type="checkbox" id="cat_54" class="docPermission  parent_cat_52" name="localPerm[]">
        <label class="strong" for="cat_54">Form 2</label>
      </li>
    </ul>
  </li>
</ul>

答案 1 :(得分:0)

代替依靠SomeParentCheckbox.trigger('change')
我们可以递归遍历父组

  • 在复选框更改时,处理后代复选框(任何深度),并将checked状态设置为与触发的复选框相同。
  • 在复选框更改时,递归遍历父级以设置checkedindeterminate属性状态

function handleDocPermParent(ckb) {
  // Get group element: (Ideally we would have a 'group' class, but sadly we don't, so let's go tricky for known common selectors)
  const $group = $(ckb).closest('ul');
  const $par   = $group.closest('li');
  
  if (!$par.length) return; // No parent? Recursion job done!
  
  const $par_ckb = $par.find(docPermClass).first(); // Find parent's main checkbox
  const $group_ckb = $group.children('li').children(docPermClass); // Collect all group's checkboxes
  
  const tot = $group_ckb.length; // How many checkboxes?
  const tot_checked = $group_ckb.filter(':checked').length; // How many siblings are checked?
  const tot_indeter = $group_ckb.filter((i, e) => e.indeterminate).length; // How many siblings are indeterminate?
  
  $par_ckb.prop({ // Finally set parent's main checkbox state:
    checked: tot_checked === tot,
    indeterminate: tot_indeter || tot_checked && tot_checked < tot
  });
  
  handleDocPermParent($par_ckb[0]); // Recursively iterate to outer parent
}

const docPermClass = '.docPermission';
const $docPerm = $(docPermClass);

$docPerm.on('change', function (evt) {
  const $ch = $(this).parent().find(docPermClass).not(this);
  $ch.prop({checked: this.checked}); // Handle inner checkboxes (in all childrens, any depth) explicitly:
  handleDocPermParent(this); // Handle parents recursively (from inner to outer) implicitly:
});
<ul>
  <li class="main">
    <input type="checkbox" id="cat_52" class="docPermission  parent_cat_0" name="localPerm[]">
    <label class="strong" for="cat_52">Forms</label>
    <ul>
      <li>
        <input type="checkbox" id="cat_53" class="docPermission  parent_cat_52" name="localPerm[]">
        <label class="strong" for="cat_53">Form 1</label>
        <ul>
          <li>
            <input type="checkbox" id="cat_55" class="docPermission  parent_cat_53" name="localPerm[]">
            <label class="strong" for="cat_55">Form 1a</label>
            <ul>
              <li>
                <input type="checkbox" id="cat_56" class="docPermission  parent_cat_55" name="localPerm[]">
                <label class="strong" for="cat_56">Form 1aa</label>
              </li>
            </ul>
          </li>
          <li class="main">
            <input type="checkbox" id="doc_80" class="docPermission  parent_cat_53" name="localPerm[]">
            <label for="doc_80">Form 1b</label>
          </li>
          <li class="main">
            <input type="checkbox" id="doc_82" class="docPermission  parent_cat_53" name="localPerm[]">
            <label for="doc_82">Form 1c</label>
          </li>
        </ul>
      </li>
      <li>
        <input type="checkbox" id="cat_54" class="docPermission  parent_cat_52" name="localPerm[]">
        <label class="strong" for="cat_54">Form 2</label>
      </li>
    </ul>
  </li>
</ul>

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>