【问题标题】:Jquery checkbox toggeling not workingJquery复选框切换不起作用
【发布时间】:2013-09-26 02:24:40
【问题描述】:

在我的 html 页面中,我想动态插入复选框,并且我希望在顶部有 1 个主复选框,因此如果选中,则所有动态创建的复选框都将被选中,如果未选中,则所有动态创建的复选框变得不受控制。我有这个代码:

<script type="text/javascript">
    $(function() {
        $("#selectAll").click(function() {
            var checked = $(this).prop('checked');
            $(".profilebox").attr("checked", checked);
        });
    });
</script> 

主复选框

<input id="selectAll" type="checkbox" name="selectall" value="All">

其他复选框:(使用此 php 代码插入循环中)

<input type='checkbox' class='profilebox' name='select' value='{$member_id}'>

但是它不能正常工作。如果我单击主控,那么它们都会被检查。如果我再次单击它,则所有内容都未选中,然后如果我再次单击它,它们仍将保持未选中状态。

有人知道这个问题吗?

谢谢

【问题讨论】:

    标签: javascript php jquery html checkbox


    【解决方案1】:

    使用prop instead of attr,保证设置元素的属性比设置元素的属性有效。较旧的 jquery 版本没有 prop,attr 用于执行两者的工作,后来引入了 prop 并用于设置像这些 prop 这样的属性是最好的。

    $(function() {
            $("#selectAll").click(function() {
                $(".profilebox").prop("checked", this.checked);
            });
        });
    

    【讨论】:

      【解决方案2】:

      需要使用.prop()来设置checked属性,而不是.attr()

      $(".profilebox").prop("checked", this.checked);
      

      例如:

      $(function () {
          //cache the selector result
          var $profileboxes = $(".profilebox");
          $("#selectAll").click(function () {
              $profileboxes.attr("checked", this.checked);
          });
      });
      

      阅读:Attributes vs. Properties

      【讨论】:

        【解决方案3】:

        使用.prop()

        $(".profilebox").prop("checked", this.checked);
        

        现在你的代码变成了

        $(function () {
            $("#selectAll").click(function () {
                $(".profilebox").prop("checked", this.checked);
            });
        });
        

        $( elem ).prop( "checked" ) true (Boolean) 会随着复选框而改变 状态

        $( elem ).attr( "checked" ) (1.6) "checked" (String) 初始状态 复选框;不会改变 $( elem ).attr( "checked" )

        (1.6.1+) "checked" (String) 会随着复选框状态而改变

        $( elem ).attr( "checked" ) (pre-1.6) true (Boolean) 更改为 复选框状态

        【讨论】:

          猜你喜欢
          • 2012-12-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-05-26
          • 1970-01-01
          • 1970-01-01
          • 2016-07-17
          • 1970-01-01
          相关资源
          最近更新 更多