【问题标题】:what the wrong in this toggle function to checked all checkboxes检查所有复选框的切换功能有什么问题
【发布时间】:2013-06-24 17:34:23
【问题描述】:

我希望在选中一个复选框时选中所有其他复选框

我使用了这个代码:

html:

<input type="checkbox" id="checkall" />

<input type="checkbox" name="rows[]" value="<?php echo $aut["aut_id"]; ?>" class="checkrow" />
<input type="checkbox" name="rows[]" value="<?php echo $aut["aut_id"]; ?>" class="checkrow" />
<input type="checkbox" name="rows[]" value="<?php echo $aut["aut_id"]; ?>" class="checkrow" />
<input type="checkbox" name="rows[]" value="<?php echo $aut["aut_id"]; ?>" class="checkrow" />
<input type="checkbox" name="rows[]" value="<?php echo $aut["aut_id"]; ?>" class="checkrow" />

jQuery:

        <script type="text/javascript">
            jQuery(document).ready(function(){                

                jQuery("#checkall").click(function () {
                    if(jQuery("#checkall").prop("checked") == true) {
                        jQuery(".checkrow").prop("checked", true);
                    }else{
                        jQuery(".checkrow").prop("checked", false);
                    }


                });
            });            
        </script>

现在,这工作正常,但我想问还有其他最简单或更直接的方法吗??

特别是我使用了这段代码,但它不起作用,我想知道是什么原因??

<script type="text/javascript">
        jQuery(document).ready(function(){

            jQuery("#checkall").click(function() {  
                jQuery(".checkrow").toggle(function() {                        
                   jQuery(this).attr("checked", "checked");
                }, function() {                        
                   jQuery(this).removeAttr("checked");
                });            
           });
        });            
    </script>

【问题讨论】:

    标签: jquery checkbox click toggle


    【解决方案1】:

    看看这个函数:

    function toggleChecked(status) {
       $("INPUT[type='checkbox']").each( function() {
       $(this).attr("checked",status);
    })
    

    这会将您页面上的所有复选框设置为状态

    【讨论】:

      【解决方案2】:

      为什么不

      jQuery(function($){                
          $("#checkall").click(function () {
              $(".checkrow").prop("checked", this.checked);
          });
      }); 
      

      【讨论】:

        【解决方案3】:

        最简单的方法,

        <input type="checkbox" name="checkall" id="checkall" onclick="$('input[type=checkbox][name^=rows]').attr('checked',this.checked)">
        

        【讨论】:

          【解决方案4】:
          jQuery(document).ready(function(){                
                          jQuery("#checkall").click(function (e) {
                              jQuery(".checkrow").prop("checked", e.target.checked);
                          });
          });      
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2011-09-19
            • 2011-11-03
            • 2011-10-20
            • 2016-11-25
            • 2011-08-23
            • 1970-01-01
            • 2023-03-29
            相关资源
            最近更新 更多