最近在做项目中,前台页面上有很多个checkBox,要根据条件来判断,哪些选中,哪些移除选中效果。
发现checkBox在使用中,第一次好用,但是取消过一次之后,再想让其变为选中状态就不行了。
由于代码是从另一个系统迁移过来的,在此系统中运行正常。但是放到自己项目中,就无法正常使用了。于是怀疑是jQuery版本问题导致的。
代码如下:
$("#topRadio input").removeAttr("checked");
$("#topRadio input").parent().removeClass("checked");
var currentDom = $(".container_7[date='" + dataChoose + "']");
if (dataJson[dataChoose].state == 0) {
currentDom.find("input[type='checkbox']").removeAttr("checked");
}
else if (dataJson[dataChoose].state == 1) {
currentDom.find("input[type='checkbox']").attr("checked", "true");
}
首先进行判断,如果不符合条件了,就removeAttr("checked"),在下一次判断的时候如果符合条件在给加上checked。
但是发现一旦移除了 attribute - checked ,在加上的时候就加不上了。
百度之后发现很多同学也一样遇到了这个问题
在做复选框全选按钮的时候,出现了一个问题,使用语句$.attr(‘checked‘,true),将复选框的属性改为被选中,在chrome浏览器中第一次点击有效后面就不行了,IE8倒是没有问题。
百度了很久找到原因是HTML的属性分为attribute和property,暂且将后者称为特性。
checked属性即分为attribute->checked,和property->true,false。
对于一个checkbox,若未定义checked="checked",alert($.attr("checked")) 的结果是undefined。若已定义则结果是checked。attribute并不随着checkbox的状态变化而改变。
使用prop($.attr("checked"))的话输出则分别为false和true。property则随其变化而变化。
所以在修改checked属性时要使用prop()。prop()在jQuery1.6版本后新增。
于是修改代码:
var currentDom = $(".container_7[date='" + dataChoose + "']");
if (dataJson[dataChoose].state == 0) {
currentDom.find("input[type='checkbox']").prop("checked",false);
}
else if (dataJson[dataChoose].state == 1) {
console.log(currentDom);
console.log(currentDom.find("input[type='checkbox']").attr("checked"));
currentDom.find("input[type='checkbox']").prop("checked", "true");
}
改为用prop来给复选框设置选中效果,问题解决。 此问题应该是jQuery版本问题,如果发现出现了这个问题:
1.不妨换个版本
2.设置checkBox的属性方法用 prop()
一直以为是,jQuery选择器的问题,没有选择到元素,坑了我好久。