jquery 学习之二 属性相关


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" /> ]
---------------------------------------------------------------------------------------------------------------------------------------
attr(key,fn)
为所有匹配的元素设置一个计算的属性值。
不提供值,而是提供一个函数,由这个函数计算的值作为属性值。
Set a single property to a computed value, on all matched elements.
Instead of supplying a string value as described 'above', a function is provided that computes the value.
返回值
jQuery

参数
key (String) : 属性名称

fn (Function) : 返回值的函数 范围:当前元素, 参数: 当前元素的索引值

示例
把src属性的值设置为title属性的值。

HTML 代码:

<img src="test.jpg"/>
jQuery 代码:

$("img").attr("title", function() { return this.src });
结果:

<img src="test.jpg" title="test.jpg" />
---------------------------------------------------------------------------------------------------------------------------------------
removeAttr(name)
从每一个匹配的元素中删除一个属性
Remove an attribute from each of the matched elements.
返回值
jQuery

参数
name (String) : 要删除的属性名

示例
将文档中图像的src属性删除

HTML 代码:

<img src="test.jpg"/>
jQuery 代码:

$("img").removeAttr("src");
结果:

[ <img /> ]
« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3