【问题标题】:Check boxes clicked all复选框全部点击
【发布时间】:2014-03-22 02:54:03
【问题描述】:

我想在单击任何子项时选择父项。此代码正在检查和检查。

$(function() {
  $(".child").on("click",function() {
      $parent = $(this).prevAll(".parent");
      if ($(this).is(":checked")) $parent.prop("checked",true);
      else {
         var len = $(this).parent().find(".child:checked").length;
         $parent.prop("checked",len>0);
      }    
  });
  $(".parent").on("click",function() {
      $(this).parent().find(".child").prop("checked",this.checked);
  });
});

它与输入一起工作(见link)

<input type='checkbox' name='cat' class='parent' value='cat1' />Category 1<br>
<input type='checkbox' name='foo' class='child' value='1' />SubCategory 1<br>
<input type='checkbox' name='foo' class='child' value='1' />SubCategory 2

但使用

  • 检查不起作用(请参阅此link)
    <input type='checkbox' name='cat' class='parent' value='cat1' />Category 1
    <ul>
        <il><input type='checkbox' name='foo' class='child' value='1' />SubCategory 1</il>
        <il><input type='checkbox' name='foo' class='child' value='1' />SubCategory 2</il>
    </ul>    
    
  • 【问题讨论】:

    • 如果你想得到答案,你应该真正展示你的代码,链接你的小提琴,并更好地解释你的问题。
    • 查看链接了解问题

    标签: javascript


    【解决方案1】:

    在查看您的代码后,我想出了一个我认为您想要的解决方案。

    通过使用自定义属性,如果选择了其中一个子复选框,我选择了顶级复选框。如果至少选中了一个子级别复选框,则父级别保持选中状态。否则,未选中。这可能比导航 DOM 更容易,最终代码更少。

    $(function() {
      $(".child").change(function() {
          if ($('.child[thisparent=' + $(this).attr('thisparent') + ']:checked').length == 0) {
              $('#' + $(this).attr('thisparent')).prop('checked', false);
          }
          else {
              $('#' + $(this).attr('thisparent')).prop('checked', true);
          }
      });
      $(".parent").change(function() {
          $('input[thisparent="' + $(this).attr('id') + '"]').prop('checked', $(this).prop('checked'));
      });
    });
    

    JSFiddle:here

    另外,您的 html 无效。你的“il”标签应该是“li”

    【讨论】:

    • 这就是我想要的,非常感谢您的帮助
    【解决方案2】:

    添加无序列表会增加另一层父子。编辑这一行:

          $parent = $(this).parent().prevAll(".parent");
    

    到这里:

      $parent = $(this).parent().parent().prevAll(".parent");
    

    正确指向您的预期父母。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-04
      • 2014-05-26
      • 1970-01-01
      • 2017-12-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多