2013-08-27 59 views
0

我遇到了jquery的問題。JQuery - 複選框不打開

我有一個複選框,ID爲「#checkAll」,複選框帶有「checkboxes」類。 我想在選中ID爲「checkAll」的複選框時打開所有複選框, ,並且當選中ID爲「checkAll」的複選框時,我想關閉所有複選框。

但是,現在發生的事情是,當我第一次點擊複選框(#checkAll)時,所有其他複選框都會打開,當我第一次打開cckckbox(#checkAll)時,其他所有複選框也會關閉。

但是,當我第二次嘗試單擊複選框(#checkAll)時,所有其他複選框都未打開。

我不知道爲什麼會發生這種情況。

請幫我一把!

這是我的JavaScript處理事件。

ADMIN.event = (function() { 

    function _init(){ 

     $(function(){ 

      var checkAll = $('#checkAll'), 
       checkboxes = $('.checkboxes'); 

      checkAll.click(function(){ 
       if($(this).is(':checked')){ 
        checkboxes.attr('checked', 'checked'); 
       } else { 
        checkboxes.removeAttr('checked'); 
       } 
      }) 

     }); 

    } 


    _init(); 


}()); 

這是我在php中的視圖文件。

<table class="fullTable"> 
    <tr class="listTableTr"> 
     <th class="listTableTh tinyTh"><input type="checkbox" name="" id="checkAll" /></th> 
     <th id="articleTitleTh" class="listTableTh">title</th> 

    </tr> 

    <?php foreach($postData as $post): ?> 

     <td class="listTableTd"><input type="checkbox" name="" class="checkboxes" /></td> 
     <td class="listTableTd"><a href="<?php echo 'index.php?r=admin/post/edit&post='.$post['id']; ?>"><?php echo $post['title'];?></a></td> 

    <?php endforeach; ?>       

</table> 
+0

如果你正在使用'jQuery的1.6 +',使用[道具](http://api.jquery.com/prop/),而不是'attr'。 – machineaddict

+0

是的,我剛剛下載了最新的Jquery。它應該是Jquery 1.6+。 – Hayato

+0

我明白了,我會嘗試prop()! – Hayato

回答

3

.prop()嘗試像

checkAll.click(function(){ 
    checkboxes.prop('checked',this.checked); 
}); 

而且它能夠更好地與.on()甚至使用像

checkAll.on('click' , function(){ 
    checkboxes.prop('checked',this.checked); 
}); 
+0

謝謝!我使用的是JQuery 1.10.2。 我會看看prop()和on()。 – Hayato

1

試試這個:

$('#checkAll').on('click',function(){ 
     if($("#checkAll").is(':checked')) { 
      $('.checkboxes').attr('checked',true); 
     } else { 
      $('.checkboxes').attr('checked',false); 
     } 
    }); 
+0

非常感謝你! – Hayato

1

DEMO
試試這個

$("#checkAll").click(function() { 
    if ($(this).is(":checked")) 
    $(".checkboxes").prop("checked","checked"); 
    else 
     $(".checkboxes").prop("checked",false); 
}); 
+0

謝謝!它也有效! – Hayato

+0

再次感謝。我給了+1! – Hayato