checkbox复选框选中和不选中时触发的时间

$(".checkboxs_yy").click(function(){

       if($(this).attr("checked")==true){
           console.log("选中");
       }else{
           console.log("未选中");
       } 
    });

.checkboxs_yy是一个复选框,我想让在选中时触发一个时间,不选中时触发另外一个事件,为何我写的这个一直是未选中,应该怎么改

阅读 8.5k
4 个回答
$(".checkboxs_yy").click(function(){
    if($(this).is(":checked")){
        console.log("选中");
    }else{
        console.log("未选中");
    }
});

$(this).is(":checked")

使用这个$(this).prop('checked')而不用$(this).attr('checked')用来获取动态可变的属性。

attr()在checkbox下不适合用来做是否被选中的判断,可以用.is(":checked")或.prop("checked", true)来做是否被选中的判断。
在jQuery API有相关说明,1.6+的jQuery要用prop,尤其是 checkBox 的 checked 的属性的判断,
同时 .is(":checked") 适合所有版本

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题