jQuery API jQuery API 中英文对照版 - jQuery在线查询手册
attr(key,fn)

attr(key, fn)

为所有匹配的元素设置一个计算的属性值。

不提供值,而是提供一个函数,由这个函数计算的值作为属性值。

返回值:jQuery

参数:

  • key (String): 要设置的属性名称
  • value (Function): 返回值的函数
 

[示例]:

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

$("img").attr("title", function() { return this.src });
HTML标记:
<img src="test.jpg" />
结果:
<img src="test.jpg" title="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.

Return value: jQuery
Parameters:

  • key (String): The name of the property to set.
  • value (Function): A function returning the value to set. Scope: Current element, argument: Index of current element

Example:

Sets title attribute from src attribute.

 $("img").attr("title", function() { return this.src });  
Before:
 <img src="test.jpg" />  
Result:
 <img src="test.jpg" title="test.jpg" />

Example:

Enumerate title attribute.

 $("img").attr("title", function(index) {
   return this.title + (++index); 
 });  
Before:
 <img title="pic" /><img title="pic" /><img title="pic" />  
Result:
 <img title="pic1" /><img title="pic2" /><img title="pic3" />