+ -
当前位置:首页 → 问答吧 → toggle方法在实现全选checkbox时有问题

toggle方法在实现全选checkbox时有问题

时间:2009-06-12

来源:互联网

对于下面这段代码,在点击全选时,别的CheckBox确实能选中,但单单全选复选框它自己不会被选中,这是为什么呀!
果如在$(this).attr("checked","checked")前加上一个alert,可以看到它先是被选中了,然后又被取消了,谁能解释一下呀!
当然,我用别的方法实现了,但没这个方法优雅呀!
复制代码
  1. <body>
  2. <script src="jquery-1.3.2.min.js"></script>
  3. <script>
  4. $(function(){
  5.     $("#checkAll").toggle(
  6.         function(){$(":checkbox").each(function(){$(this).attr("checked","checked")})},
  7.         function(){$(":checkbox").each(function(){$(this).attr("checked","")})}
  8.     )
  9. })
  10. </script>
  11. <input type="checkbox" />a<br />
  12. <input type="checkbox" />b<br />
  13. <input type="checkbox" />c<br />
  14. <input type="checkbox" />d<br />
  15. <input type="checkbox" />e<br />
  16. <input type="checkbox" />f<br />
  17. <input type="checkbox" id="checkAll" />全选<br />
  18. </body>

作者: ljzforever   发布时间: 2009-06-12

因为你点的时候是选上的...toggle()后就会被取消...
你在toggle()后在把它选上就好了...
新人说话..呵呵!!!

作者: jamix   发布时间: 2009-06-12

说的有道理呀,但是如何才能在toggle的架构内就搞定呢?

作者: ljzforever   发布时间: 2009-06-12

$("#checkAll").click(function(){
           $(":checkbox").attr("checked",this.checked)
})

作者: shawphy   发布时间: 2009-06-12

关注

作者: konglx   发布时间: 2009-06-13

不实践一下么?只是关注么?

作者: shawphy   发布时间: 2009-06-13

3楼的方法不错

作者: xueyepaomo   发布时间: 2009-06-15

可不可以不用toggle啊?
复制代码
  1. <script language="javascript" type="text/javascript">
  2. $(function() {
  3.     $("#CheckAll").click(function() {
  4.                 $("#divCheckBox>:checkbox").attr("checked", this.checked);
  5.             });
  6.     $("#divCheckBox>:checkbox").click(function() {
  7.                 var count = $("#divCheckBox>:checkbox").size();
  8.                 var checkedCount = $("#divCheckBox>:checkbox[checked='true']").size();
  9.                 $("#CheckAll").attr("checked", count == checkedCount);
  10.             });
  11.         })
  12. </script>
  13. <input id="CheckAll" type="checkbox" />Check All
  14.     <div id="divCheckBox">
  15.         <input type="checkbox"/>
  16.         <input type="checkbox" />
  17.         <input type="checkbox" />
  18.         <input type="checkbox" />
  19.         <input type="checkbox" />
  20.         <input type="checkbox" />
  21.         <input type="checkbox" />
  22.         <input type="checkbox" />
  23.         <input type="checkbox" />
  24.     </div>

作者: e_wait   发布时间: 2009-06-17

$("#CheckAll").click(function() {
    alert("Select All.");
    $("input:checkbox").each(function() {
    this.checked=true;
  });
});

这样不是更好么?

作者: mike_zhao   发布时间: 2009-07-14

最为新手我觉得8楼的挺好的,没有其他的那么复杂

作者: 李清   发布时间: 2009-07-15

<script>
$(function(){
    $("#checkAll").toggle(function(){
        $('input').attr('checked',true);
    },function(){
        $('input').attr('checked',false);
    });
});
</script>
永远的选中

作者: zjfeihu   发布时间: 2009-07-15

相关阅读 更多