jQuery文档里有一段很精辟的描述:
Properties generally affect the dynamic state of a DOM element without changing the serialized HTML attribute.
Examples include the value property of input elements, the disabled property of inputs and buttons, or the checked property of a checkbox.
The .prop() method should be used to set disabled and checked instead of the .attr() method.
The .val() method should be used for getting and setting value.
prop是指动态改变一个DOM元素的状态而不改变HTML的源码,如input元素的value、disabled、checked等,通过prop来改变disabled、checked的值,用val来改变value值。
通过attr改的属性会反应到html源码里,而prop不会。如:
F12查看一下,会发现testAttr已经加到html源码里,而prop则不会,但是prop确实能取到这个属性,是不是有点$.data的赶脚,但是只能设置string、number、bool值。$('input[name="reports_mode"]').prop('testProp', 'prop');
$('input[name="reports_mode"]').attr('testAttr', 'attr'); alert($('input[name="reports_mode"]').prop('testProp') + $('input[name="reports_mode"]').attr('testAttr'));
换句话讲,用attr改checked实际上改的不是checkbox的状态,而是更改了defaultChecked的属性值,即仅仅是设置了初始值,而prop改checked则会更改checkbox的状态。Nevertheless, the most important concept to remember about the checked attribute is that it does not correspond to the checked property.
The attribute actually corresponds to the defaultChecked property and should be used only to set the initial value of the checkbox.
The checked attribute value does not change with the state of the checkbox, while the checked property does.
Therefore, the cross-browser-compatible way to determine if a checkbox is checked is to use the property:
if ( elem.checked )
if ( $( elem ).prop( "checked" ) )
if ( $( elem ).is( ":checked" ) )
The same is true for other dynamic attributes, such as selected and value.
看jQuery源码:
attr用的是element的setAttribute、getAttribute方法,prop用的是element.***。
总之,获取、更改checked、disabled、selected用prop(不要removeProp这几个内置的属性),获取、更改value用val,其他的用attr。