jquery 手册
Ajax
属性(Attributes)
回调对象(Callbacks ..
核心(Core)
CSS
数据(Data)
延迟对象(Deferred o ..
尺寸(Dimensions)
效果(Effects)
事件(Events)
表单(Forms)
文档操作(Manipulati ..
杂项(Miscellaneou ..
位置(Offset)
插件编写(Plugin Aut ..
属性(Properties)
选择器(Selectors)
遍历(Traversing)
工具(Utilities)

Returns: StringString .attr( String attributeName )

Description: Get the value of an attribute for the first element in the set of matched elements.
  • version added: 1.0
  • .attr( String attributeName )
  • attributeName The name of the attribute to get.

The .attr() method gets the attribute value for only the first element in the matched set. To get the value for each element individually, use a looping construct such as jQuery's .each() or .map() method.

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. In addition, .attr() should not be used on plain objects, arrays, the window, or the document. To retrieve and change DOM properties, use the .prop() method.

Using jQuery's .attr() method to get the value of an element's attribute has two main benefits:

  1. Convenience: It can be called directly on a jQuery object and chained to other jQuery methods.
  2. Cross-browser consistency: The values of some attributes are reported inconsistently across browsers, and even across versions of a single browser. The .attr() method reduces such inconsistencies.

Note: Attribute values are strings with the exception of a few attributes such as value and tabindex.

Examples:

Example:

Find the title attribute of the first <em> in the page.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>em { color:blue; font-weight;bold; }
  div { color:red; }</style>
</head>
<body>
  
<p>
  Once there was a <em title="huge, gigantic">large</em> dinosaur...
</p>

  The title of the emphasis is:<div></div>

  <script>var title = $("em").attr("title");
  $("div").text(title);</script>
</body>
</html>

Demo:

Returns: jQueryjQuery .attr( String attributeName, Function function(index, attr) )

Description: Set one or more attributes for the set of matched elements.
  • version added: 1.0
  • .attr( String attributeName, String,Number value )
  • attributeName The name of the attribute to set.
    value A value to set for the attribute.
  • version added: 1.0
  • .attr( Map map )
  • map A map of attribute-value pairs to set.
  • version added: 1.1
  • .attr( String attributeName, Function function(index, attr) )
  • attributeName The name of the attribute to set.
    function(index, attr) A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old attribute value as arguments.

The .attr() method is a convenient way to set the value of attributes—especially when setting multiple attributes or using values returned by a function. Consider the following image:

<img id="greatphoto" src="brush-seller.jpg" alt="brush seller" />

Setting a simple attribute

To change the alt attribute, simply pass the name of the attribute and its new value to the .attr() method:

$('#greatphoto').attr('alt', 'Beijing Brush Seller');

Add an attribute the same way:

$('#greatphoto')
.attr('title', 'Photo by Kelly Clark');

Setting several attributes at once

To change the alt attribute and add the title attribute at the same time, pass both sets of names and values into the method at once using a map (JavaScript object literal). Each key-value pair in the map adds or modifies an attribute:

$('#greatphoto').attr({
  alt: 'Beijing Brush Seller',
  title: 'photo by Kelly Clark'
});

When setting multiple attributes, the quotes around attribute names are optional.

WARNING: When setting the 'class' attribute, you must always use quotes!

Note: jQuery prohibits changing the type attribute on an <input> or <button> element and will throw an error in all browsers. This is because the type attribute cannot be changed in Internet Explorer.

Computed attribute values

By using a function to set attributes, you can compute the value based on other properties of the element. For example, to concatenate a new value with an existing value:

$('#greatphoto').attr('title', function(i, val) {
  return val + ' - photo by Kelly Clark'
});

This use of a function to compute attribute values can be particularly useful when modifying the attributes of multiple elements at once.

Note: If nothing is returned in the setter function (ie. function(index, attr){}), or if undefined is returned, the current value is not changed. This is useful for selectively setting values only when certain criteria are met.

Examples:

Example:

Set some attributes for all <img>s in the page.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>img { padding:10px; }
  div { color:red; font-size:24px; }</style>
</head>
<body>
  
  <img />
  <img />
  <img />

  <div><B>Attribute of Ajax</B></div>

  <script>$("img").attr({ 
  src: "/images/hat.gif",
  title: "jQuery",
  alt: "jQuery Logo"
});
$("div").text($("img").attr("alt"));</script>
</body>
</html>

Demo:

Example:

Set the id for divs based on the position in the page.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style>div { color:blue; }
  span { color:red; }
  b { font-weight:bolder; }</style>
</head>
<body>
  
  <div>Zero-th <span></span></div>
  <div>First <span></span></div>
  <div>Second <span></span></div>

  <script>$("div").attr("id", function (arr) {
  return "div-id" + arr;
})
.each(function () {
  $("span", this).html("(ID = '<b>" + this.id + "</b>')");
});</script>
</body>
</html>

Demo:

Example:

Set the src attribute from title attribute on the image.
<!DOCTYPE html>
<html>
<head>
  <script src="../jquery.min.js"></script>
  <style></style>
</head>
<body>
  
<img title="hat.gif"/>

  <script>$("img").attr("src", function() { 
    return "/images/" + this.title; 
});</script>
</body>
</html>

Demo: