search

Home  >  Q&A  >  body text

javascript - js一个奇怪的问题

我想为页面提供一个全选的功能,于是写了一个jquery.

<script type="text/javascript">
    $('#selectAll').click(function(){
        if(this.checked){
            $('.select').each(
                    function(){
                        $(this).attr('checked',true);
                    }
            );
            console.log('true');
        }else
        {
            $('.select').each(
                    function(){
                        $(this).removeAttr('checked');
                    }
            );
            console.log('false');
        }
    });
</script>

我在页面运行,元素的checked属性在变化,但是页面就是不渲染效果打钩和不打勾,只有刚载入是页面时执行一次。

PHPzPHPz2902 days ago497

reply all(2)I'll reply

  • ringa_lee

    ringa_lee2017-04-10 14:58:55

    使用prop而非attr

    $("#selectAll").on("click",function(){
        if($(this).prop("checked")){
          $("input[type='checkbox']:not(#selectAll)").prop("checked",true);
          console.log('true');
        }
        else{
          $("input[type='checkbox']:not(#selectAll)").prop("checked",false);
          console.log('false');
        }
      })
    

    reply
    0
  • PHPz

    PHPz2017-04-10 14:58:55

    <input type="checkbox" id="selectAll"/>
    <input type="checkbox" />
    <input type="checkbox" />
    <input type="checkbox" />
    <input type="checkbox" />
    <input type="checkbox" />
    <input type="checkbox" />
    <input type="checkbox" />
    
    $("#selectAll").click(function(){
        $("input[type='checkbox']:not(#selectAll)").attr("checked",$(this).attr("checked") == 'checked')
    })
    

    reply
    0
  • Cancelreply