为什么这个jQuery代码检查所有复选框不起作用?

时间:2012-08-11 16:00:04

标签: javascript jquery

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');,则代码有效。问题可能出在选择器

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

5 个答案:

答案 0 :(得分:7)

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

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

诀窍。

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

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

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

答案 1 :(得分:1)

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

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

答案 2 :(得分: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');

用于调试here

答案 3 :(得分:1)

据我所知,只要表格格式正确,表格就可以包含任何块级别或内联元素。问题是表格必须包含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

答案 4 :(得分:0)

使用它,它可以正常工作:

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

});​

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