首页 > js一个奇怪的问题

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属性在变化,但是页面就是不渲染效果打钩和不打勾,只有刚载入是页面时执行一次。


<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')
})

使用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');
    }
  })
【热门文章】
【热门文章】