- attr 表示HTML文档节点属性
- prop表示JS对象属性 (jquery版本1.6+)
区别:在1.6版本前,attr()获取的是初始化值,除非通过attr(‘name’,’value’)改变,但是这个方法可能导致不一致的行为;在1.6版本开始prop()获取属性值是动态的,比如checkbox,选中后,checked变为true,prop值也会发生改变。
$("input").prop("disabled", false);//设置disable 为falseif ($("input").prop("disabled")) { //do something alert("disabled is :true");} else { //do something alert("disabled is :false");}$("input").prop("checked", true);if ($("input").prop("checked")) { //do something alert("disabled is :true");} else { //do something alert("disabled is :false");}
官方提供的资料:
elem.checked | true (Boolean) Will change with checkbox state |
---|---|
$( elem ).prop( "checked" ) | true (Boolean) Will change with checkbox state |
elem.getAttribute( "checked" ) | "checked" (String) Initial state of the checkbox; does not change |
$( elem ).attr( "checked" ) (1.6) | "checked" (String) Initial state of the checkbox; does not change |
$( elem ).attr( "checked" ) (1.6.1+) | "checked" (String) Will change with checkbox state |
$( elem ).attr( "checked" ) (pre-1.6) | true (Boolean) Changed with checkbox state |
prop demo