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

阅读 3.2k
2 个回答

使用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');
    }
  })
<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')
})
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题