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

attr(key, value)

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

可以是由${规则}表达式提供的计算值,见示例2。

注意,不能在IE中设置input元素的name属性。可以使用$(html)或.append(html)或.html(html)动态地创建包含name属性的input元素。

返回值:jQuery

参数:

  • key (String): 要设置的属性名称
  • value (Object): 设置属性的值
 
[示例]:

为所有图像设置src属性。

$("img").attr("src","test.jpg");
HTML标记:
<img/>
结果:
<img src="test.jpg"/>
[示例]:

以src属性的值作为title属性的值。使用了attr(String,Function)的简写方式。

$("img").attr("title", "${this.src}");
HTML标记:
<img src="test.jpg" />
结果:
<img src="test.jpg" title="test.jpg" />
 
attr( key, value)

Set a single property to a value, on all matched elements.

Note that you can't set the name property of input elements in IE. Use $(html) or .append(html) or .html(html) to create elements on the fly including the name property.

Return value: jQuery
Parameters:

  • key (String): The name of the property to set.
  • value (Object): The value to set the property to.
 

Example:

Sets src attribute to all images.

 $("img").attr("src","test.jpg");  

Before:

 <img/>  
Result:
 <img src="test.jpg"/>