返回值:Stringattr(attributeName)
Get the value of an attribute for the first element in the set of matched elements.
-
1.0 新增attr(attributeName)
attributeName (String) The name of the attribute to get.
It's important to note that the .attr()
method gets the attribute value for only the first element in the matched set. To get the value for each element individually, we need to rely on a looping construct such as
jQuery's .each()
or .map()
method.
Using jQuery's .attr()
method to get the value of an element's attribute has two main benefits:
- Convenience: It can be called directly on a jQuery object and chained to other jQuery methods.
-
Cross-browser consistency: Some attributes have inconsistent naming from browser to browser. Furthermore, the values of some attributes are reported
inconsistently across browsers, and even across versions of a single browser. The
.attr()
method reduces such inconsistencies.
If we try to get the value of an attribute that has not been set, the .attr()
method returns undefined
.
示例:
Finds the title attribute of the first <em> in the page.
<!DOCTYPE html>
<html>
<head>
<style>em { color:blue; font-weight;bold; }
div { color:red; }</style>
<script src="jquery.min.js"></script>
</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>