【问题标题】:Checking all immediate parent checkboxes in JQuery检查 JQuery 中的所有直接父复选框
【发布时间】:2011-09-14 05:33:46
【问题描述】:

我有这个嵌套列表结构。我的树可以升到 n 级。

如果选中孩子,我想要一个只能选择父母的 JQuery 选择器。

<ul id="treeFeatureList">
<li>
    <input type="checkbox" name="selectedRole">
    Application Manager
    <ul>
        <li>
            <input type="checkbox" name="selectedRole">
            Application Manager Panel
        </li>
        <li>
            <input type="checkbox" name="selectedRole">
            Client Role
            <ul>
                <li>
                    <input type="checkbox" name="selectedRole">
                    Client Task 1
                </li>
                <li>
                    <input type="checkbox" name="selectedRole">
                    Client Task 2
                </li>
            </ul>
        </li>
    </ul>
</li>
</ul>

我想要什么:如果选中了客户端任务 1 或任务 2,则客户端角色和应用程序管理器也被选中了。绝对不是应用程序管理器面板(应该保持未选中状态)。

感谢帮助制作这个神奇的选择器。

【问题讨论】:

    标签: jquery-selectors checkbox html-lists


    【解决方案1】:
    $('input[type="checkbox"]').change(function() {
        if ($(this).is(':checked')) {
            $(this).parents('ul').siblings('input:checkbox').attr('checked', true);
        }
        else
        {
            $(this).parents('ul').siblings('input:checkbox').attr('checked', false);
        }
    });
    

    Here 是一个演示。

    【讨论】:

      【解决方案2】:

      .closest().siblings() 的组合应该可以满足您的需求。您需要选择已检查输入的最接近的祖先,它是具有“父”复选框的兄弟,然后遍历该复选框。代码看起来像这样:

      $('input:checkbox').change(function() {
          //if you are using < jQuery 1.6, use .attr() instead of .prop()
          if (this.checked) {
              $(this).closest('ul').siblings('input:checkbox').prop('checked', true);
          }
      });
      

      Here is a live demo ->

      【讨论】:

        【解决方案3】:
        $('input[type="checkbox"]').change(function() {
        if ($(this).is(':checked')) {
            $(this).parents('ul').siblings('input:checkbox').attr('checked', true);
        } else {
                //if any of the sibling is checked, do not  uncheck the main category
                var isSiblingChecked = false;
                $(this).parent().siblings().each(function() {
                    if (($(this).find('input[type="checkbox"]').is(':checked'))) {
                        isSiblingChecked = true;
                    }
                });     
                if (isSiblingChecked == false) {            
            $(this).parents('ul').siblings('input:checkbox').attr('checked', false);
                }
        }
        });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-02-02
          • 1970-01-01
          • 2017-05-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-09-27
          相关资源
          最近更新 更多