问题描述
为实现行选中功能,使用jQuery来控制checkbox的选中状态,但是第一次点击出现选中样式,之后点击可以看到checked的属性增加成功但是并没有选中状态。
问题代码
selectQuotationRows : function(index){
var self = this;
var checkbox = $(event.target).parent().find('.eachCK');
checkbox.attr('checked', typeof(checkbox.attr('checked')) == undefined ? true : !checkbox.attr('checked'));
//do something ……
}
解决办法
selectQuotationRows : function(index){
var self = this;
var checkbox = $(event.target).parent().find('.eachCK');
checkbox.prop('checked', !checkbox.prop('checked'));
//do something ……
}
总结
使用 attr() 给属性 checked 赋值,发现无论赋予什么值,只要给这个属性赋值了就是选中状态,使用
.
attr('checked','true');
和.
attr('checked','false'),结果都是选中状态,可以使用attr()和removeAttr(),或者使用.attr('checked', true);和.attr('checked',false),但是使用attr()出现了只有第一次会出现选中和取消选中的状态,后面点击没有选中状态但是代码显示对checked属性控制成功的,只能改为使用prop() 或者使用javascript原生代码来控制,才不会出现上述情况。