attr(name)
取得第一个匹配元素的属性值。通过这个方法可以方便地从第一个匹配元素中获取一个属性的值。如果元素没有相应属性,则返回 undefined 。
Access a property on the first matched element. This method makes it easy to retrieve a property value from the first matched element. If the element does not have an attribute with such a name, undefined is returned.
返回值
Object
参数
name (String) : 属性名称
示例
返回文档中第一个图像的src属性值。
HTML 代码:
<img src=”test.jpg”/>
jQuery 代码:
$(“img”).attr(“src”);
结果:
test.jpg
—————————————————————————————————————————————
attr(properties)
将一个“名/值”形式的对象设置为所有匹配元素的属性。
这是一种在所有匹配元素中批量设置很多属性的最佳方式。 注意,如果你要设置对象的class属性,你必须使用’className’ 作为属性名。或者你可以直接使用.addClass( class ) 和 .removeClass( class ).
Set a key/value object as properties to all matched elements.
This serves as the best way to set a large number of properties on all matched elements. Note that you must use ‘className’ as key if you want to set the class-Attribute. Or use .addClass( class ) or .removeClass( class ).
返回值
jQuery
参数
properties (Map) : 作为属性的“名/值对”对象
示例
为所有图像设置src和alt属性。
HTML 代码:
<img/>
jQuery 代码:
$(“img”).attr({ src: “test.jpg”, alt: “Test Image” });
结果:
[ <img src= “test.jpg” alt:=”Test Image” /> ]
—————————————————————————————————————————————
attr(key,value)
为所有匹配的元素设置一个属性值。
Set a single property to a value, on all matched elements.
返回值
jQuery
参数
key (String) : 属性名称
value (Object) : 属性值
示例
为所有图像设置src属性。
HTML 代码:
<img/>
<img/>
jQuery 代码:
$(“img”).attr(“src”,”test.jpg”);
结果:
[ <img src= “test.jpg” /> , <img src= “test.jpg” /> ]
—————————————————————————————————————————————










