jquery的一些常见的问题

380 阅读1分钟

如何确认checkbox是否被选中和改变checkbox的选中状态

$(this).is(':checked');   //true    false
$(this).attr("checked",true)  //选中
$(this).attr("checked",false)  //未选中
//这两个是有区别的
$(this).prop("checked",true)
$(this).prop("checked",false)

原来,在jquery里,有两种操作元素属性的方法,一种是attr(),另一种是prop().

attr()是用来改变元素的attributes属性的,而prop()方法是用来改变元素properties属性的,那么这两者有何区别呢。

在默认情况下,attributes和properties是一样的,都是用来保存元素的属性值的。

但是,当涉及到boolean值时,比如checkbox这样的,有true和false这样的布尔值的元素属性,attributes在页面加载的时候就被设置,并且一直保持初始值,而properties则存储着元素属性的当前值。

也就是说:boolean properties保持最新。但相应的boolean attributes是不一样的,正如上面所述,它们仅被浏览器用来保存初始值

所以,涉及到boolean properties要在页面加载后随时更新的话,那还是要使用prop()方法。

反选代码

//反选

$("#unchecked").click(function(){
        $("input[type='checkbox']:lt(5)").each(function(){ 
                    if($(this).is(':checked')) { 
                        $(this).prop("checked",false);
                    }else{ 
                        $(this).prop("checked",true);
                    } 
        })
})

全选或者全不选

$("#qx").click(function(event) {
        var xx=$(this).is(':checked'); 
        if(xx==true){
            $("input[type='checkbox']").each(function(){
                $(this).prop("checked",true)
            })
        }else{
            $("input[type='checkbox']").each(function(){
                $(this).prop("checked",false)
            })

        }
});