1

Yesterday i was giving an answer to one of the stackoverflow question that How to check/uncheck all checkboxes based on the selection of one checkbox and i came up with this solution. But the problem is it only works once but it will not work if you click it twice. FIDDLE

$('#allcb').click(function(){
    if ($('#allcb').is(':checked'))
    {
      $('.chk').each(function(){
        $(this).attr('checked', true);
      });
    }
    else
    {
        $('.chk').each(function(){
           $(this).attr('checked', false);
        });
    }
});

I found this code which works fine according to the requirements FIDDLE

So what is wrong with my approach? Either it should not work at all. If it works once why its not works twice?

4

1 回答 1

6

它只工作一次的原因是因为你应该使用过prop(),而不是attr().

prop()更改属性,如element.checked,同时attr()更改属性,如<input type="radio" checked="checked" />,并且更改属性不会更改属性,这本质上是您想要的,因为更改属性只会起作用一次,因为下次检查属性时会出现背对面的属性。

有关prop 和 attr 之间区别的概述,请参阅此SO question 。

$('#allcb').click(function(){
    if ($('#allcb').is(':checked'))
    {
      $('.chk').each(function(){
        $(this).prop('checked', true);
      });
    }
    else
    {
        $('.chk').each(function(){
           $(this).prop('checked', false);
        });
    }
});

小提琴

作为旁注,该代码可以总结为:

$('#allcb').on('click', function(){
    $('.chk').prop('checked', this.checked);
});

小提琴

于 2013-07-24T13:20:06.240 回答