HTML:

<table class="responsive" id="products">
    <a href="#" id="checkAllProducts">Do it</a>
    <input type="checkbox">
    <input type="checkbox">
    <input type="checkbox">
</table>


JS:

$(document).ready(function(){
  $('#checkAllProducts').click(function(){
    var checkbox = $('#products input:checkbox');
    checkbox.attr('checked',!checkbox.attr('checked'));
  });
});​


它可用于调试here

如果执行var checkbox = $('input:checkbox');,则代码有效。问题可能出在选择器中

单击链接后,此代码应选中所有复选框。但这没有做到。为什么?

最佳答案

据我所知,只要表格格式正确,表格就可以包含任何块级别或内联元素。问题在于表必须具有tdtr和shit之类的东西来定义它的行和行,如果尝试:

<table class="responsive" id="products">
    <tr>
        <td>
            <a href="#" id="checkAllProducts">Do it</a>
            <input type="checkbox">
            <input type="checkbox">
            <input type="checkbox">
        </td>
    </tr>
</table>


它将正常工作,然后您可以执行以下操作:

$(function(){
  $('#checkAllProducts').on('click', function(e){
      e.preventDefault();
      var checkbox = $('#products input[type="checkbox"]');
      checkbox.prop('checked', !checkbox.prop('checked'));
  });
});


FIDDLE

09-30 16:21
查看更多