【问题标题】:Toggle check/uncheck for multiple checkbox lists using jQuery使用 jQuery 切换选中/取消选中多个复选框列表
【发布时间】:2012-02-22 00:00:57
【问题描述】:

我在选中和取消选中(全选和取消全选)复选框列表时遇到两个问题:

  1. 父复选框不选中/取消选中。
  2. 我只需要选择孩子。

例子:

http://jsfiddle.net/TheFiddler/v6wmV/,

$(document).ready(function(){
    $('.all').toggle(
        function() {
            $('.check').find('input[type=checkbox]').attr('checked', true);
        },
        function() {
            $('.check').find('input[type=checkbox]').attr('checked', false);
        });
});

现在,我有一个班级的事件,由于班级由两个复选框列表共享,它们都切换。

【问题讨论】:

标签: jquery checkbox toggle


【解决方案1】:

Demo

$(document).ready(function(){ 
    $('.all').click(function() {
        var $checkboxes = $(this).parent().find('input[type=checkbox]');
        $checkboxes.prop('checked', $(this).is(':checked'));
    });     
});  

HTML

<div class="check">
      <input type="checkbox" class="all" /> Check/Uncheck all<br />
      <input type="checkbox" /> 1<br />
      <input type="checkbox" /> 2<br />
      <input type="checkbox" /> 3<br />
      <input type="checkbox" /> 4<br />
      <input type="checkbox" /> 5<br />
      <input type="checkbox" /> 6<br />
      <input type="checkbox" /> 7
</div>
...

【讨论】:

  • 这绝对有效,但你不需要 "?true : false" 部分,因为 "$(this).is(':checked')" 已经返回 true 或 false。这就像说“如果(真){真}否则{假}”
  • 其实需要一个!$(this).is('checked'),否则什么都不做。
【解决方案2】:

上面的帖子不错。使用每个函数的另一种方式,尽管它不只使用子函数。

jQuery('.check-all').click(function() {
      jQuery('.checked-rec').each(function() {
        $(this).attr('checked', $('.check-all').is(':checked'));
      })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<thead>
  <tr>
    <th>
      <input type="checkbox" class="check-all">
    </th>
  </tr>
</thead>

<tbody>

  <tr class="odd gradeX">
    <td>
      <input type="checkbox" class="checked-rec">
    </td>
  </tr>

  <tr class="odd gradeX">
    <td>
      <input type="checkbox" class="checked-rec">
    </td>
  </tr>

  <tr class="odd gradeX">
    <td>
      <input type="checkbox" class="checked-rec">
    </td>
  </tr>

  <tr class="odd gradeX">
    <td>
      <input type="checkbox" class="checked-rec">
    </td>
  </tr>

</tbody>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-22
    • 2017-01-04
    • 1970-01-01
    • 1970-01-01
    • 2013-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多