jQuery中attr() 和 prop()【转】

Version 1.9.0 开始不建议使用 attr() 来对具有 true 和 false 两个属性的属性进行操作。

具有 true 和 false 两个属性的属性,如 checked, selected 或者 disabled 建议使用prop(),其他的使用 attr()。

示例代码:

1 <input id="chk1" type="checkbox" />
2 <input id="chk2" type="checkbox" checked="checked" />
3 
4 $("#chk1").prop("checked") == false
5 $("#chk2").prop("checked") == true
6 
7 $("#chk1").attr("checked") == undefined
8 $("#chk2").attr("checked") == "checked"

Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes,which could cause inconsistent behavior.

To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.

以上。

SEE ALSO 1

SEE ALSO 2

原文地址:https://www.cnblogs.com/hzj680539/p/5027502.html