jQuery检查所有复选框只工作一次

jQuery check all checkboxes works only once

本文关键字:一次 工作 检查 复选框 jQuery      更新时间:2023-09-26

为什么Chrome上的这个功能第二次不能工作?

$('.main').on('change','input[name="select_all"]',function(){
   if($(this).is(':checked')){
      $('input[type="checkbox"]',$(this).parent().parent().parent()).attr('checked',true);
   }else{
      $('input[type="checkbox"]',$(this).parent().parent().parent()).removeAttr('checked');
});

第一次点击时,它会全部选中,第二次则会全部取消选中。。。但在第三局什么也没做。。。

jsfiddle

PS。它确实添加和删除了选中的属性,但在视觉上不会发生更改。

铬31.0.1650.57 m

使用prop而不是attr:

$('.main').on('change','input[name="select_all"]',function(){
    if($(this).is(':checked')){
        $('input[type="checkbox"]',$(this).parent().parent().parent()).prop('checked',true);
    }else{
        $('input[type="checkbox"]',$(this).parent().parent().parent()).prop('checked', false);
    }
});

jQuery文档解释了差异,并列出了一些应该使用prop的情况。

$('.main').on('change','input[name="select_all"]',function(){
   if($(this).is(':checked')){
      $('input[type="checkbox"]',$(this).parent().parent().parent()).attr('checked',true);
   }else{
  $('input[type="checkbox"]',$(this).parent().parent().parent()).attr('checked',false);
});

我希望这就是您正在寻找的