0

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');。问题可能出在选择器中

单击链接后,此代码应检查所有复选框。但它不这样做。为什么?

4

5 回答 5

7

您的 HTML 无效。您不能将input元素直接放在table元素内。当浏览器发现下一个元素不能跟随表格标签时,很可能会自动关闭表格标签 - 因此无法找到复选框作为#products选择器的子项。

<div class="responsive" id="products">

成功了。

此外,“checked”是一个属性,所以你应该使用 prop() 来访问它:

checkbox.prop('checked', !checkbox.prop('checked'));

http://jsfiddle.net/UNqfv/6/

于 2012-08-11T16:05:29.903 回答
1
var checkbox = $('#products input:checkbox');

checkbox不是单个复选框,您需要调用.each()对所有复选框进行操作..

于 2012-08-11T16:03:49.370 回答
1

html 表格元素必须包含 tr、td 标签。

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

并且您的选择器代码应该相似

var checkbox = $('#products tr td input:checkbox');

在这里调试

于 2012-08-11T17:47:04.343 回答
1

据我所知,只要表格格式正确,表格可以包含任何块级或内联元素。问题是一个表必须有像和shit这样的东西tdtr定义它的行和行,如果你尝试:

<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'));
  });
});

小提琴​​​​​</p>

于 2012-08-11T19:35:01.747 回答
0

使用它,它会工作得很好:

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

});​

原因是您需要指定“所有检查块”。目前使用选择器“$('#products input:checkbox');”,您只选择 id 为“products”的复选框。如果您在每个名为“产品”的复选框上都有一个 id 属性,那么您的原始代码将起作用。相反,我在上面向您展示的选择器将选择任何复选框类型。希望这会有所帮助,并且解释清楚!快乐编码!

于 2012-08-12T00:07:30.790 回答