方便
:它可以直接被jQuery对象访问并且链式调用其他jQuery方法。
浏览器兼容
:一些属性在不同浏览器中得到不同的值。 甚至在同一个浏览器的不同版本中。
.attr()
方法减少了兼容性问题。
注意:
除少数属性意外,属性值都是字符串,如value和tabindex。
试图改变通过HTML创建的,或已经在HTML文档中的
input
元素的
type
特性(attribute)或属性(property),在Internet Explorer 6, 7, or 8下将会抛出一个错误。
在jQuery 1.6中
,当属性没有被设置时候,
.attr()
方法将返回
undefined
。
另外,
.attr()
不应该用在普通的对象,数组,窗口(window)或文件(document)上。
若要检索和更改DOM属性,比如元素的
checked
,
selected
, 或
disabled
状态,请使用
.prop()
方法。
Attributes vs. Properties
attributes
和
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)是目前存在,
即使,该属性没有对应的值,或者被设置为空字符串值,或甚至是"false",相应的属性(property)为true。
这才是真正的所有布尔属性(attributes)。
然而,要记住的最重要的概念是
checked
特性(attribute)不是对应它
checked
属性(property)。特性(attribute)实际对应的是
defaultChecked
属性(property),而且仅用于设置复选框最初的值。
checked
特性(attribute)值不会因为复选框的状态而改变,而
checked
属性(property)会因为复选框的状态而改变。因此,
跨浏览器兼容的方法来确定一个复选框是否被选中,是使用该属性(property):
if ( elem.checked )
if ( $(elem).prop("checked") )
if ( $(elem).is(":checked") )
em { color:blue; font-weight:bold; }
<script src="https://code.jquery.com/jquery-latest.js"></script>
Once there was a <em title="huge, gigantic">large</em> dinosaur...
The title of the emphasis is:<div></div>
var title = $("em").attr("title");
当设置多个属性,包裹属性名的引号是可选的。
警告:
当设置样式名(“class”)属性时,必须使用引号!
注意
: jQuery禁止改变一个
<input>
或
<button>
元素的
type
特性(attribute),并且在所有浏览器下将抛出一个错误。因为Internet Explorer不会允许你改变
<input>
或者
<button>
元素的
type
属性。
Computed attribute values(推算属性值)
通过使用一个函数来设置属性, 可以根据该元素上的其它属性值返回最终所需的属性值。例如,我们可以把新的值与现有的值联系在一起:
当前运用一个函数来计算属性的值,当我们修改了多个元素的属性,特别有用。
注意
如果setter函数没有返回任何数据(例如:
function(index, attr){})
,属性的当前值返回值是undefined,作为一个getter行为。实际上,如果不进行任何更改的setter函数不返回的东西。
Example:
为页面中全部的 <img>设置一些属性。
div { color:red; font-size:24px; }
<script src="https://code.jquery.com/jquery-latest.js"></script>
<div><B>Attribute of Ajax</B></div>
$("div").text($("img").attr("alt"));
b { font-weight:bolder; }
<script src="https://code.jquery.com/jquery-latest.js"></script>
<div>Zero-th <span></span></div>
<div>First <span></span></div>
<div>Second <span></span></div>
$("div").attr("id", function (arr) {
$("span", this).html("(ID = '<b>" + this.id + "</b>')");