87,920
社区成员
发帖
与我相关
我的任务
分享
$("input").attr("checked","checked")
$("input")[0].checked = true;
if($("#checkAll")[0].checked) {
$(".checkIt").each(function(){this.checked = true;})
}
老生长谈的问题,归根结底是这俩的区别:
checkboxElement.setAttribute('checked','checked');
checkboxElement.checked = true;
类似的还有:inputElement.value, optionElement.selected, inputElement.disabled....
如果某个版本的jQ在某个浏览器下用attr("checked","checked")能生效,那只能说明jQ做了特殊的treat,对已经存在于DOM中的checkbox来说,其UI表现(UI上选中与否)也即真实值,与checkboxElement.checked这个布尔值是时时对应更新的,那个Attribute只在浏览器第一次渲染这个控件的时候作为初始值之用,setAttribute无法时时更新UI(真实值)。
论attribute和property(属性和属性,中文居然也匮乏了。。。)。
参见:http://www.w3help.org/zh-cn/causes/SD9006
例如,考虑一个DOM元素的HTML标记中定义的<input type="checkbox" checked="checked" /> ,并假设它是一个JavaScript变量命名的elem :
elem.checked true (Boolean) 将改变复选框的状态
$(elem).prop("checked") true (Boolean) 将改变复选框的状态
elem.getAttribute("checked") "checked" (String) 不会改变的复选框的初始状态;
$(elem).attr("checked") (1.6) "checked" (String) 不会改变的复选框的初始状态;
$(elem).attr("checked") (1.6.1+) "checked" (String) 将改变复选框的状态
$(elem).attr("checked") (pre-1.6) true (Boolean) 将改变复选框的状态
$("input").prop("checked",true);
ttributes和properties之间的差异在特定情况下是很重要。jQuery 1.6之前 ,.attr()方法在取某些 attribute 的值时,会返回 property 的值,这就导致了结果的不一致。从 jQuery 1.6 开始, .prop()方法 方法返回 property 的值,而 .attr() 方法返回 attributes 的值。
例如, selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, 和 defaultSelected 应使用.prop()方法进行取值或赋值。 在jQuery1.6之前,这些属性使用.attr()方法取得,但是这并不是元素的attr属性。他们没有相应的属性(attributes),只有特性(property)。
例如,考虑一个DOM元素的HTML标记中定义的<input type="checkbox" checked="checked" /> ,并假设它是一个JavaScript变量命名的elem :
elem.checked true (Boolean) 将改变复选框的状态
$(elem).prop("checked") true (Boolean) 将改变复选框的状态
elem.getAttribute("checked") "checked" (String) 不会改变的复选框的初始状态;
$(elem).attr("checked") (1.6) "checked" (String) 不会改变的复选框的初始状态;
$(elem).attr("checked") (1.6.1+) "checked" (String) 将改变复选框的状态
$(elem).attr("checked") (pre-1.6) true (Boolean) 将改变复选框的状态
根据W3C的表单规范 ,在checked属性是一个布尔属性,这意味着只要该 attribute 存在,即使它没有值,或是一个空字符串,该属性对应的 property 就是 true。以下推荐的是兼容浏览器方式,判断 checkbox 元素的 checked 属性是否为"真" 的方法:
if ( elem.checked )
if ( $(elem).prop("checked") )
if ( $(elem).is(":checked") )
如果你使用jQuery 1.6 ,代码if ( $(elem).attr("checked") ),将获得一个属性(attribute) ,它不改变该复选框被选中和选中。它只是用来存储默认或选中属性的初始值。为了保持向后兼容,.attr() 方法从 jQuery 1.6.1+ 开始除了返回属性值外,还会更新 property 属性,因此 boolean attribute(布尔属性)不需要通过 .prop() 来改变其值。推荐使用上述方法之一,来取得 checked 的值。